xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 2caf0dcd2abc26b477e317999994020212790d38)
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 2006 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 
32 
33 
34 
35 #include <sys/scsi/scsi.h>
36 #include <sys/dkbad.h>
37 #include <sys/dklabel.h>
38 #include <sys/dkio.h>
39 #include <sys/fdio.h>
40 #include <sys/cdio.h>
41 #include <sys/mhd.h>
42 #include <sys/vtoc.h>
43 #include <sys/dktp/fdisk.h>
44 #include <sys/file.h>
45 #include <sys/stat.h>
46 #include <sys/kstat.h>
47 #include <sys/vtrace.h>
48 #include <sys/note.h>
49 #include <sys/thread.h>
50 #include <sys/proc.h>
51 #include <sys/efi_partition.h>
52 #include <sys/var.h>
53 #include <sys/aio_req.h>
54 
55 #ifdef __lock_lint
56 #define	_LP64
57 #define	__amd64
58 #endif
59 
60 #if (defined(__fibre))
61 /* Note: is there a leadville version of the following? */
62 #include <sys/fc4/fcal_linkapp.h>
63 #endif
64 #include <sys/taskq.h>
65 #include <sys/uuid.h>
66 #include <sys/byteorder.h>
67 #include <sys/sdt.h>
68 
69 #include "sd_xbuf.h"
70 
71 #include <sys/scsi/targets/sddef.h>
72 
73 
74 /*
75  * Loadable module info.
76  */
77 #if (defined(__fibre))
78 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver %I%"
79 char _depends_on[]	= "misc/scsi drv/fcp";
80 #else
81 #define	SD_MODULE_NAME	"SCSI Disk Driver %I%"
82 char _depends_on[]	= "misc/scsi";
83 #endif
84 
85 /*
86  * Define the interconnect type, to allow the driver to distinguish
87  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
88  *
89  * This is really for backward compatability. In the future, the driver
90  * should actually check the "interconnect-type" property as reported by
91  * the HBA; however at present this property is not defined by all HBAs,
92  * so we will use this #define (1) to permit the driver to run in
93  * backward-compatability mode; and (2) to print a notification message
94  * if an FC HBA does not support the "interconnect-type" property.  The
95  * behavior of the driver will be to assume parallel SCSI behaviors unless
96  * the "interconnect-type" property is defined by the HBA **AND** has a
97  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
98  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
99  * Channel behaviors (as per the old ssd).  (Note that the
100  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
101  * will result in the driver assuming parallel SCSI behaviors.)
102  *
103  * (see common/sys/scsi/impl/services.h)
104  *
105  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
106  * since some FC HBAs may already support that, and there is some code in
107  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
108  * default would confuse that code, and besides things should work fine
109  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
110  * "interconnect_type" property.
111  */
112 #if (defined(__fibre))
113 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
114 #else
115 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
116 #endif
117 
118 /*
119  * The name of the driver, established from the module name in _init.
120  */
121 static	char *sd_label			= NULL;
122 
123 /*
124  * Driver name is unfortunately prefixed on some driver.conf properties.
125  */
126 #if (defined(__fibre))
127 #define	sd_max_xfer_size		ssd_max_xfer_size
128 #define	sd_config_list			ssd_config_list
129 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
130 static	char *sd_config_list		= "ssd-config-list";
131 #else
132 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
133 static	char *sd_config_list		= "sd-config-list";
134 #endif
135 
136 /*
137  * Driver global variables
138  */
139 
140 #if (defined(__fibre))
141 /*
142  * These #defines are to avoid namespace collisions that occur because this
143  * code is currently used to compile two seperate driver modules: sd and ssd.
144  * All global variables need to be treated this way (even if declared static)
145  * in order to allow the debugger to resolve the names properly.
146  * It is anticipated that in the near future the ssd module will be obsoleted,
147  * at which time this namespace issue should go away.
148  */
149 #define	sd_state			ssd_state
150 #define	sd_io_time			ssd_io_time
151 #define	sd_failfast_enable		ssd_failfast_enable
152 #define	sd_ua_retry_count		ssd_ua_retry_count
153 #define	sd_report_pfa			ssd_report_pfa
154 #define	sd_max_throttle			ssd_max_throttle
155 #define	sd_min_throttle			ssd_min_throttle
156 #define	sd_rot_delay			ssd_rot_delay
157 
158 #define	sd_retry_on_reservation_conflict	\
159 					ssd_retry_on_reservation_conflict
160 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
161 #define	sd_resv_conflict_name		ssd_resv_conflict_name
162 
163 #define	sd_component_mask		ssd_component_mask
164 #define	sd_level_mask			ssd_level_mask
165 #define	sd_debug_un			ssd_debug_un
166 #define	sd_error_level			ssd_error_level
167 
168 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
169 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
170 
171 #define	sd_tr				ssd_tr
172 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
173 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
174 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
175 #define	sd_check_media_time		ssd_check_media_time
176 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
177 #define	sd_label_mutex			ssd_label_mutex
178 #define	sd_detach_mutex			ssd_detach_mutex
179 #define	sd_log_buf			ssd_log_buf
180 #define	sd_log_mutex			ssd_log_mutex
181 
182 #define	sd_disk_table			ssd_disk_table
183 #define	sd_disk_table_size		ssd_disk_table_size
184 #define	sd_sense_mutex			ssd_sense_mutex
185 #define	sd_cdbtab			ssd_cdbtab
186 
187 #define	sd_cb_ops			ssd_cb_ops
188 #define	sd_ops				ssd_ops
189 #define	sd_additional_codes		ssd_additional_codes
190 
191 #define	sd_minor_data			ssd_minor_data
192 #define	sd_minor_data_efi		ssd_minor_data_efi
193 
194 #define	sd_tq				ssd_tq
195 #define	sd_wmr_tq			ssd_wmr_tq
196 #define	sd_taskq_name			ssd_taskq_name
197 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
198 #define	sd_taskq_minalloc		ssd_taskq_minalloc
199 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
200 
201 #define	sd_dump_format_string		ssd_dump_format_string
202 
203 #define	sd_iostart_chain		ssd_iostart_chain
204 #define	sd_iodone_chain			ssd_iodone_chain
205 
206 #define	sd_pm_idletime			ssd_pm_idletime
207 
208 #define	sd_force_pm_supported		ssd_force_pm_supported
209 
210 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
211 
212 #endif
213 
214 
215 #ifdef	SDDEBUG
216 int	sd_force_pm_supported		= 0;
217 #endif	/* SDDEBUG */
218 
219 void *sd_state				= NULL;
220 int sd_io_time				= SD_IO_TIME;
221 int sd_failfast_enable			= 1;
222 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
223 int sd_report_pfa			= 1;
224 int sd_max_throttle			= SD_MAX_THROTTLE;
225 int sd_min_throttle			= SD_MIN_THROTTLE;
226 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
227 int sd_qfull_throttle_enable		= TRUE;
228 
229 int sd_retry_on_reservation_conflict	= 1;
230 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
231 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
232 
233 static int sd_dtype_optical_bind	= -1;
234 
235 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
236 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
237 
238 /*
239  * Global data for debug logging. To enable debug printing, sd_component_mask
240  * and sd_level_mask should be set to the desired bit patterns as outlined in
241  * sddef.h.
242  */
243 uint_t	sd_component_mask		= 0x0;
244 uint_t	sd_level_mask			= 0x0;
245 struct	sd_lun *sd_debug_un		= NULL;
246 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
247 
248 /* Note: these may go away in the future... */
249 static uint32_t	sd_xbuf_active_limit	= 512;
250 static uint32_t sd_xbuf_reserve_limit	= 16;
251 
252 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
253 
254 /*
255  * Timer value used to reset the throttle after it has been reduced
256  * (typically in response to TRAN_BUSY or STATUS_QFULL)
257  */
258 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
259 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
260 
261 /*
262  * Interval value associated with the media change scsi watch.
263  */
264 static int sd_check_media_time		= 3000000;
265 
266 /*
267  * Wait value used for in progress operations during a DDI_SUSPEND
268  */
269 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
270 
271 /*
272  * sd_label_mutex protects a static buffer used in the disk label
273  * component of the driver
274  */
275 static kmutex_t sd_label_mutex;
276 
277 /*
278  * sd_detach_mutex protects un_layer_count, un_detach_count, and
279  * un_opens_in_progress in the sd_lun structure.
280  */
281 static kmutex_t sd_detach_mutex;
282 
283 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
284 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
285 
286 /*
287  * Global buffer and mutex for debug logging
288  */
289 static char	sd_log_buf[1024];
290 static kmutex_t	sd_log_mutex;
291 
292 
293 /*
294  * "Smart" Probe Caching structs, globals, #defines, etc.
295  * For parallel scsi and non-self-identify device only.
296  */
297 
298 /*
299  * The following resources and routines are implemented to support
300  * "smart" probing, which caches the scsi_probe() results in an array,
301  * in order to help avoid long probe times.
302  */
303 struct sd_scsi_probe_cache {
304 	struct	sd_scsi_probe_cache	*next;
305 	dev_info_t	*pdip;
306 	int		cache[NTARGETS_WIDE];
307 };
308 
309 static kmutex_t	sd_scsi_probe_cache_mutex;
310 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
311 
312 /*
313  * Really we only need protection on the head of the linked list, but
314  * better safe than sorry.
315  */
316 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
317     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
318 
319 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
320     sd_scsi_probe_cache_head))
321 
322 
323 /*
324  * Vendor specific data name property declarations
325  */
326 
327 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
328 
329 static sd_tunables seagate_properties = {
330 	SEAGATE_THROTTLE_VALUE,
331 	0,
332 	0,
333 	0,
334 	0,
335 	0,
336 	0,
337 	0,
338 	0
339 };
340 
341 
342 static sd_tunables fujitsu_properties = {
343 	FUJITSU_THROTTLE_VALUE,
344 	0,
345 	0,
346 	0,
347 	0,
348 	0,
349 	0,
350 	0,
351 	0
352 };
353 
354 static sd_tunables ibm_properties = {
355 	IBM_THROTTLE_VALUE,
356 	0,
357 	0,
358 	0,
359 	0,
360 	0,
361 	0,
362 	0,
363 	0
364 };
365 
366 static sd_tunables purple_properties = {
367 	PURPLE_THROTTLE_VALUE,
368 	0,
369 	0,
370 	PURPLE_BUSY_RETRIES,
371 	PURPLE_RESET_RETRY_COUNT,
372 	PURPLE_RESERVE_RELEASE_TIME,
373 	0,
374 	0,
375 	0
376 };
377 
378 static sd_tunables sve_properties = {
379 	SVE_THROTTLE_VALUE,
380 	0,
381 	0,
382 	SVE_BUSY_RETRIES,
383 	SVE_RESET_RETRY_COUNT,
384 	SVE_RESERVE_RELEASE_TIME,
385 	SVE_MIN_THROTTLE_VALUE,
386 	SVE_DISKSORT_DISABLED_FLAG,
387 	0
388 };
389 
390 static sd_tunables maserati_properties = {
391 	0,
392 	0,
393 	0,
394 	0,
395 	0,
396 	0,
397 	0,
398 	MASERATI_DISKSORT_DISABLED_FLAG,
399 	MASERATI_LUN_RESET_ENABLED_FLAG
400 };
401 
402 static sd_tunables pirus_properties = {
403 	PIRUS_THROTTLE_VALUE,
404 	0,
405 	PIRUS_NRR_COUNT,
406 	PIRUS_BUSY_RETRIES,
407 	PIRUS_RESET_RETRY_COUNT,
408 	0,
409 	PIRUS_MIN_THROTTLE_VALUE,
410 	PIRUS_DISKSORT_DISABLED_FLAG,
411 	PIRUS_LUN_RESET_ENABLED_FLAG
412 };
413 
414 #endif
415 
416 #if (defined(__sparc) && !defined(__fibre)) || \
417 	(defined(__i386) || defined(__amd64))
418 
419 
420 static sd_tunables elite_properties = {
421 	ELITE_THROTTLE_VALUE,
422 	0,
423 	0,
424 	0,
425 	0,
426 	0,
427 	0,
428 	0,
429 	0
430 };
431 
432 static sd_tunables st31200n_properties = {
433 	ST31200N_THROTTLE_VALUE,
434 	0,
435 	0,
436 	0,
437 	0,
438 	0,
439 	0,
440 	0,
441 	0
442 };
443 
444 #endif /* Fibre or not */
445 
446 static sd_tunables lsi_properties_scsi = {
447 	LSI_THROTTLE_VALUE,
448 	0,
449 	LSI_NOTREADY_RETRIES,
450 	0,
451 	0,
452 	0,
453 	0,
454 	0,
455 	0
456 };
457 
458 static sd_tunables symbios_properties = {
459 	SYMBIOS_THROTTLE_VALUE,
460 	0,
461 	SYMBIOS_NOTREADY_RETRIES,
462 	0,
463 	0,
464 	0,
465 	0,
466 	0,
467 	0
468 };
469 
470 static sd_tunables lsi_properties = {
471 	0,
472 	0,
473 	LSI_NOTREADY_RETRIES,
474 	0,
475 	0,
476 	0,
477 	0,
478 	0,
479 	0
480 };
481 
482 static sd_tunables lsi_oem_properties = {
483 	0,
484 	0,
485 	LSI_OEM_NOTREADY_RETRIES,
486 	0,
487 	0,
488 	0,
489 	0,
490 	0,
491 	0
492 };
493 
494 
495 
496 #if (defined(SD_PROP_TST))
497 
498 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
499 #define	SD_TST_THROTTLE_VAL	16
500 #define	SD_TST_NOTREADY_VAL	12
501 #define	SD_TST_BUSY_VAL		60
502 #define	SD_TST_RST_RETRY_VAL	36
503 #define	SD_TST_RSV_REL_TIME	60
504 
505 static sd_tunables tst_properties = {
506 	SD_TST_THROTTLE_VAL,
507 	SD_TST_CTYPE_VAL,
508 	SD_TST_NOTREADY_VAL,
509 	SD_TST_BUSY_VAL,
510 	SD_TST_RST_RETRY_VAL,
511 	SD_TST_RSV_REL_TIME,
512 	0,
513 	0,
514 	0
515 };
516 #endif
517 
518 /* This is similiar to the ANSI toupper implementation */
519 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
520 
521 /*
522  * Static Driver Configuration Table
523  *
524  * This is the table of disks which need throttle adjustment (or, perhaps
525  * something else as defined by the flags at a future time.)  device_id
526  * is a string consisting of concatenated vid (vendor), pid (product/model)
527  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
528  * the parts of the string are as defined by the sizes in the scsi_inquiry
529  * structure.  Device type is searched as far as the device_id string is
530  * defined.  Flags defines which values are to be set in the driver from the
531  * properties list.
532  *
533  * Entries below which begin and end with a "*" are a special case.
534  * These do not have a specific vendor, and the string which follows
535  * can appear anywhere in the 16 byte PID portion of the inquiry data.
536  *
537  * Entries below which begin and end with a " " (blank) are a special
538  * case. The comparison function will treat multiple consecutive blanks
539  * as equivalent to a single blank. For example, this causes a
540  * sd_disk_table entry of " NEC CDROM " to match a device's id string
541  * of  "NEC       CDROM".
542  *
543  * Note: The MD21 controller type has been obsoleted.
544  *	 ST318202F is a Legacy device
545  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
546  *	 made with an FC connection. The entries here are a legacy.
547  */
548 static sd_disk_config_t sd_disk_table[] = {
549 #if defined(__fibre) || defined(__i386) || defined(__amd64)
550 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
551 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
552 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
553 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
554 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
555 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
556 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
557 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
558 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
559 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
560 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
561 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
562 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
563 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
564 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
565 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
566 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
567 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
568 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
569 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
570 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
571 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
572 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
573 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
574 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
575 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
576 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
577 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
578 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
579 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
580 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
581 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
582 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
583 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
584 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
585 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
586 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
587 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
588 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
589 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
590 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
591 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
592 			SD_CONF_BSET_BSY_RETRY_COUNT|
593 			SD_CONF_BSET_RST_RETRIES|
594 			SD_CONF_BSET_RSV_REL_TIME,
595 		&purple_properties },
596 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
597 		SD_CONF_BSET_BSY_RETRY_COUNT|
598 		SD_CONF_BSET_RST_RETRIES|
599 		SD_CONF_BSET_RSV_REL_TIME|
600 		SD_CONF_BSET_MIN_THROTTLE|
601 		SD_CONF_BSET_DISKSORT_DISABLED,
602 		&sve_properties },
603 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
604 			SD_CONF_BSET_BSY_RETRY_COUNT|
605 			SD_CONF_BSET_RST_RETRIES|
606 			SD_CONF_BSET_RSV_REL_TIME,
607 		&purple_properties },
608 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
609 		SD_CONF_BSET_LUN_RESET_ENABLED,
610 		&maserati_properties },
611 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
612 		SD_CONF_BSET_NRR_COUNT|
613 		SD_CONF_BSET_BSY_RETRY_COUNT|
614 		SD_CONF_BSET_RST_RETRIES|
615 		SD_CONF_BSET_MIN_THROTTLE|
616 		SD_CONF_BSET_DISKSORT_DISABLED|
617 		SD_CONF_BSET_LUN_RESET_ENABLED,
618 		&pirus_properties },
619 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
620 		SD_CONF_BSET_NRR_COUNT|
621 		SD_CONF_BSET_BSY_RETRY_COUNT|
622 		SD_CONF_BSET_RST_RETRIES|
623 		SD_CONF_BSET_MIN_THROTTLE|
624 		SD_CONF_BSET_DISKSORT_DISABLED|
625 		SD_CONF_BSET_LUN_RESET_ENABLED,
626 		&pirus_properties },
627 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
628 		SD_CONF_BSET_NRR_COUNT|
629 		SD_CONF_BSET_BSY_RETRY_COUNT|
630 		SD_CONF_BSET_RST_RETRIES|
631 		SD_CONF_BSET_MIN_THROTTLE|
632 		SD_CONF_BSET_DISKSORT_DISABLED|
633 		SD_CONF_BSET_LUN_RESET_ENABLED,
634 		&pirus_properties },
635 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
636 		SD_CONF_BSET_NRR_COUNT|
637 		SD_CONF_BSET_BSY_RETRY_COUNT|
638 		SD_CONF_BSET_RST_RETRIES|
639 		SD_CONF_BSET_MIN_THROTTLE|
640 		SD_CONF_BSET_DISKSORT_DISABLED|
641 		SD_CONF_BSET_LUN_RESET_ENABLED,
642 		&pirus_properties },
643 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
644 		SD_CONF_BSET_NRR_COUNT|
645 		SD_CONF_BSET_BSY_RETRY_COUNT|
646 		SD_CONF_BSET_RST_RETRIES|
647 		SD_CONF_BSET_MIN_THROTTLE|
648 		SD_CONF_BSET_DISKSORT_DISABLED|
649 		SD_CONF_BSET_LUN_RESET_ENABLED,
650 		&pirus_properties },
651 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
652 		SD_CONF_BSET_NRR_COUNT|
653 		SD_CONF_BSET_BSY_RETRY_COUNT|
654 		SD_CONF_BSET_RST_RETRIES|
655 		SD_CONF_BSET_MIN_THROTTLE|
656 		SD_CONF_BSET_DISKSORT_DISABLED|
657 		SD_CONF_BSET_LUN_RESET_ENABLED,
658 		&pirus_properties },
659 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
660 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
661 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
662 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
663 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
664 #endif /* fibre or NON-sparc platforms */
665 #if ((defined(__sparc) && !defined(__fibre)) ||\
666 	(defined(__i386) || defined(__amd64)))
667 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
668 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
669 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
670 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
671 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
672 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
673 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
674 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
675 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
676 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
677 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
678 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
679 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
680 	    &symbios_properties },
681 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
682 	    &lsi_properties_scsi },
683 #if defined(__i386) || defined(__amd64)
684 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
685 				    | SD_CONF_BSET_READSUB_BCD
686 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
687 				    | SD_CONF_BSET_NO_READ_HEADER
688 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
689 
690 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
691 				    | SD_CONF_BSET_READSUB_BCD
692 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
693 				    | SD_CONF_BSET_NO_READ_HEADER
694 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
695 #endif /* __i386 || __amd64 */
696 #endif /* sparc NON-fibre or NON-sparc platforms */
697 
698 #if (defined(SD_PROP_TST))
699 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
700 				| SD_CONF_BSET_CTYPE
701 				| SD_CONF_BSET_NRR_COUNT
702 				| SD_CONF_BSET_FAB_DEVID
703 				| SD_CONF_BSET_NOCACHE
704 				| SD_CONF_BSET_BSY_RETRY_COUNT
705 				| SD_CONF_BSET_PLAYMSF_BCD
706 				| SD_CONF_BSET_READSUB_BCD
707 				| SD_CONF_BSET_READ_TOC_TRK_BCD
708 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
709 				| SD_CONF_BSET_NO_READ_HEADER
710 				| SD_CONF_BSET_READ_CD_XD4
711 				| SD_CONF_BSET_RST_RETRIES
712 				| SD_CONF_BSET_RSV_REL_TIME
713 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
714 #endif
715 };
716 
717 static const int sd_disk_table_size =
718 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
719 
720 
721 /*
722  * Return codes of sd_uselabel().
723  */
724 #define	SD_LABEL_IS_VALID		0
725 #define	SD_LABEL_IS_INVALID		1
726 
727 #define	SD_INTERCONNECT_PARALLEL	0
728 #define	SD_INTERCONNECT_FABRIC		1
729 #define	SD_INTERCONNECT_FIBRE		2
730 #define	SD_INTERCONNECT_SSA		3
731 #define	SD_IS_PARALLEL_SCSI(un)		\
732 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
733 
734 /*
735  * Definitions used by device id registration routines
736  */
737 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
738 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
739 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
740 #define	WD_NODE			7	/* the whole disk minor */
741 
742 static kmutex_t sd_sense_mutex = {0};
743 
744 /*
745  * Macros for updates of the driver state
746  */
747 #define	New_state(un, s)        \
748 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
749 #define	Restore_state(un)	\
750 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
751 
752 static struct sd_cdbinfo sd_cdbtab[] = {
753 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
754 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
755 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
756 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
757 };
758 
759 /*
760  * Specifies the number of seconds that must have elapsed since the last
761  * cmd. has completed for a device to be declared idle to the PM framework.
762  */
763 static int sd_pm_idletime = 1;
764 
765 /*
766  * Internal function prototypes
767  */
768 
769 #if (defined(__fibre))
770 /*
771  * These #defines are to avoid namespace collisions that occur because this
772  * code is currently used to compile two seperate driver modules: sd and ssd.
773  * All function names need to be treated this way (even if declared static)
774  * in order to allow the debugger to resolve the names properly.
775  * It is anticipated that in the near future the ssd module will be obsoleted,
776  * at which time this ugliness should go away.
777  */
778 #define	sd_log_trace			ssd_log_trace
779 #define	sd_log_info			ssd_log_info
780 #define	sd_log_err			ssd_log_err
781 #define	sdprobe				ssdprobe
782 #define	sdinfo				ssdinfo
783 #define	sd_prop_op			ssd_prop_op
784 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
785 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
786 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
787 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
788 #define	sd_spin_up_unit			ssd_spin_up_unit
789 #define	sd_enable_descr_sense		ssd_enable_descr_sense
790 #define	sd_set_mmc_caps			ssd_set_mmc_caps
791 #define	sd_read_unit_properties		ssd_read_unit_properties
792 #define	sd_process_sdconf_file		ssd_process_sdconf_file
793 #define	sd_process_sdconf_table		ssd_process_sdconf_table
794 #define	sd_sdconf_id_match		ssd_sdconf_id_match
795 #define	sd_blank_cmp			ssd_blank_cmp
796 #define	sd_chk_vers1_data		ssd_chk_vers1_data
797 #define	sd_set_vers1_properties		ssd_set_vers1_properties
798 #define	sd_validate_geometry		ssd_validate_geometry
799 
800 #if defined(_SUNOS_VTOC_16)
801 #define	sd_convert_geometry		ssd_convert_geometry
802 #endif
803 
804 #define	sd_resync_geom_caches		ssd_resync_geom_caches
805 #define	sd_read_fdisk			ssd_read_fdisk
806 #define	sd_get_physical_geometry	ssd_get_physical_geometry
807 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
808 #define	sd_update_block_info		ssd_update_block_info
809 #define	sd_swap_efi_gpt			ssd_swap_efi_gpt
810 #define	sd_swap_efi_gpe			ssd_swap_efi_gpe
811 #define	sd_validate_efi			ssd_validate_efi
812 #define	sd_use_efi			ssd_use_efi
813 #define	sd_uselabel			ssd_uselabel
814 #define	sd_build_default_label		ssd_build_default_label
815 #define	sd_has_max_chs_vals		ssd_has_max_chs_vals
816 #define	sd_inq_fill			ssd_inq_fill
817 #define	sd_register_devid		ssd_register_devid
818 #define	sd_get_devid_block		ssd_get_devid_block
819 #define	sd_get_devid			ssd_get_devid
820 #define	sd_create_devid			ssd_create_devid
821 #define	sd_write_deviceid		ssd_write_deviceid
822 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
823 #define	sd_setup_pm			ssd_setup_pm
824 #define	sd_create_pm_components		ssd_create_pm_components
825 #define	sd_ddi_suspend			ssd_ddi_suspend
826 #define	sd_ddi_pm_suspend		ssd_ddi_pm_suspend
827 #define	sd_ddi_resume			ssd_ddi_resume
828 #define	sd_ddi_pm_resume		ssd_ddi_pm_resume
829 #define	sdpower				ssdpower
830 #define	sdattach			ssdattach
831 #define	sddetach			ssddetach
832 #define	sd_unit_attach			ssd_unit_attach
833 #define	sd_unit_detach			ssd_unit_detach
834 #define	sd_set_unit_attributes		ssd_set_unit_attributes
835 #define	sd_create_minor_nodes		ssd_create_minor_nodes
836 #define	sd_create_errstats		ssd_create_errstats
837 #define	sd_set_errstats			ssd_set_errstats
838 #define	sd_set_pstats			ssd_set_pstats
839 #define	sddump				ssddump
840 #define	sd_scsi_poll			ssd_scsi_poll
841 #define	sd_send_polled_RQS		ssd_send_polled_RQS
842 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
843 #define	sd_init_event_callbacks		ssd_init_event_callbacks
844 #define	sd_event_callback		ssd_event_callback
845 #define	sd_cache_control		ssd_cache_control
846 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
847 #define	sd_make_device			ssd_make_device
848 #define	sdopen				ssdopen
849 #define	sdclose				ssdclose
850 #define	sd_ready_and_valid		ssd_ready_and_valid
851 #define	sdmin				ssdmin
852 #define	sdread				ssdread
853 #define	sdwrite				ssdwrite
854 #define	sdaread				ssdaread
855 #define	sdawrite			ssdawrite
856 #define	sdstrategy			ssdstrategy
857 #define	sdioctl				ssdioctl
858 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
859 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
860 #define	sd_checksum_iostart		ssd_checksum_iostart
861 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
862 #define	sd_pm_iostart			ssd_pm_iostart
863 #define	sd_core_iostart			ssd_core_iostart
864 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
865 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
866 #define	sd_checksum_iodone		ssd_checksum_iodone
867 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
868 #define	sd_pm_iodone			ssd_pm_iodone
869 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
870 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
871 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
872 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
873 #define	sd_buf_iodone			ssd_buf_iodone
874 #define	sd_uscsi_strategy		ssd_uscsi_strategy
875 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
876 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
877 #define	sd_uscsi_iodone			ssd_uscsi_iodone
878 #define	sd_xbuf_strategy		ssd_xbuf_strategy
879 #define	sd_xbuf_init			ssd_xbuf_init
880 #define	sd_pm_entry			ssd_pm_entry
881 #define	sd_pm_exit			ssd_pm_exit
882 
883 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
884 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
885 
886 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
887 #define	sdintr				ssdintr
888 #define	sd_start_cmds			ssd_start_cmds
889 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
890 #define	sd_bioclone_alloc		ssd_bioclone_alloc
891 #define	sd_bioclone_free		ssd_bioclone_free
892 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
893 #define	sd_shadow_buf_free		ssd_shadow_buf_free
894 #define	sd_print_transport_rejected_message	\
895 					ssd_print_transport_rejected_message
896 #define	sd_retry_command		ssd_retry_command
897 #define	sd_set_retry_bp			ssd_set_retry_bp
898 #define	sd_send_request_sense_command	ssd_send_request_sense_command
899 #define	sd_start_retry_command		ssd_start_retry_command
900 #define	sd_start_direct_priority_command	\
901 					ssd_start_direct_priority_command
902 #define	sd_return_failed_command	ssd_return_failed_command
903 #define	sd_return_failed_command_no_restart	\
904 					ssd_return_failed_command_no_restart
905 #define	sd_return_command		ssd_return_command
906 #define	sd_sync_with_callback		ssd_sync_with_callback
907 #define	sdrunout			ssdrunout
908 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
909 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
910 #define	sd_reduce_throttle		ssd_reduce_throttle
911 #define	sd_restore_throttle		ssd_restore_throttle
912 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
913 #define	sd_init_cdb_limits		ssd_init_cdb_limits
914 #define	sd_pkt_status_good		ssd_pkt_status_good
915 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
916 #define	sd_pkt_status_busy		ssd_pkt_status_busy
917 #define	sd_pkt_status_reservation_conflict	\
918 					ssd_pkt_status_reservation_conflict
919 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
920 #define	sd_handle_request_sense		ssd_handle_request_sense
921 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
922 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
923 #define	sd_validate_sense_data		ssd_validate_sense_data
924 #define	sd_decode_sense			ssd_decode_sense
925 #define	sd_print_sense_msg		ssd_print_sense_msg
926 #define	sd_extract_sense_info_descr	ssd_extract_sense_info_descr
927 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
928 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
929 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
930 #define	sd_sense_key_medium_or_hardware_error	\
931 					ssd_sense_key_medium_or_hardware_error
932 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
933 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
934 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
935 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
936 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
937 #define	sd_sense_key_default		ssd_sense_key_default
938 #define	sd_print_retry_msg		ssd_print_retry_msg
939 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
940 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
941 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
942 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
943 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
944 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
945 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
946 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
947 #define	sd_pkt_reason_default		ssd_pkt_reason_default
948 #define	sd_reset_target			ssd_reset_target
949 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
950 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
951 #define	sd_taskq_create			ssd_taskq_create
952 #define	sd_taskq_delete			ssd_taskq_delete
953 #define	sd_media_change_task		ssd_media_change_task
954 #define	sd_handle_mchange		ssd_handle_mchange
955 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
956 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
957 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
958 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
959 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
960 					sd_send_scsi_feature_GET_CONFIGURATION
961 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
962 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
963 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
964 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
965 					ssd_send_scsi_PERSISTENT_RESERVE_IN
966 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
967 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
968 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
969 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
970 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
971 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
972 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
973 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
974 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
975 #define	sd_alloc_rqs			ssd_alloc_rqs
976 #define	sd_free_rqs			ssd_free_rqs
977 #define	sd_dump_memory			ssd_dump_memory
978 #define	sd_uscsi_ioctl			ssd_uscsi_ioctl
979 #define	sd_get_media_info		ssd_get_media_info
980 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
981 #define	sd_dkio_get_geometry		ssd_dkio_get_geometry
982 #define	sd_dkio_set_geometry		ssd_dkio_set_geometry
983 #define	sd_dkio_get_partition		ssd_dkio_get_partition
984 #define	sd_dkio_set_partition		ssd_dkio_set_partition
985 #define	sd_dkio_partition		ssd_dkio_partition
986 #define	sd_dkio_get_vtoc		ssd_dkio_get_vtoc
987 #define	sd_dkio_get_efi			ssd_dkio_get_efi
988 #define	sd_build_user_vtoc		ssd_build_user_vtoc
989 #define	sd_dkio_set_vtoc		ssd_dkio_set_vtoc
990 #define	sd_dkio_set_efi			ssd_dkio_set_efi
991 #define	sd_build_label_vtoc		ssd_build_label_vtoc
992 #define	sd_write_label			ssd_write_label
993 #define	sd_clear_vtoc			ssd_clear_vtoc
994 #define	sd_clear_efi			ssd_clear_efi
995 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
996 #define	sd_setup_next_xfer		ssd_setup_next_xfer
997 #define	sd_dkio_get_temp		ssd_dkio_get_temp
998 #define	sd_dkio_get_mboot		ssd_dkio_get_mboot
999 #define	sd_dkio_set_mboot		ssd_dkio_set_mboot
1000 #define	sd_setup_default_geometry	ssd_setup_default_geometry
1001 #define	sd_update_fdisk_and_vtoc	ssd_update_fdisk_and_vtoc
1002 #define	sd_check_mhd			ssd_check_mhd
1003 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1004 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1005 #define	sd_sname			ssd_sname
1006 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1007 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1008 #define	sd_take_ownership		ssd_take_ownership
1009 #define	sd_reserve_release		ssd_reserve_release
1010 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1011 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1012 #define	sd_persistent_reservation_in_read_keys	\
1013 					ssd_persistent_reservation_in_read_keys
1014 #define	sd_persistent_reservation_in_read_resv	\
1015 					ssd_persistent_reservation_in_read_resv
1016 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1017 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1018 #define	sd_mhdioc_release		ssd_mhdioc_release
1019 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1020 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1021 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1022 #define	sr_change_blkmode		ssr_change_blkmode
1023 #define	sr_change_speed			ssr_change_speed
1024 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1025 #define	sr_pause_resume			ssr_pause_resume
1026 #define	sr_play_msf			ssr_play_msf
1027 #define	sr_play_trkind			ssr_play_trkind
1028 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1029 #define	sr_read_subchannel		ssr_read_subchannel
1030 #define	sr_read_tocentry		ssr_read_tocentry
1031 #define	sr_read_tochdr			ssr_read_tochdr
1032 #define	sr_read_cdda			ssr_read_cdda
1033 #define	sr_read_cdxa			ssr_read_cdxa
1034 #define	sr_read_mode1			ssr_read_mode1
1035 #define	sr_read_mode2			ssr_read_mode2
1036 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1037 #define	sr_sector_mode			ssr_sector_mode
1038 #define	sr_eject			ssr_eject
1039 #define	sr_ejected			ssr_ejected
1040 #define	sr_check_wp			ssr_check_wp
1041 #define	sd_check_media			ssd_check_media
1042 #define	sd_media_watch_cb		ssd_media_watch_cb
1043 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1044 #define	sr_volume_ctrl			ssr_volume_ctrl
1045 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1046 #define	sd_log_page_supported		ssd_log_page_supported
1047 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1048 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1049 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1050 #define	sd_range_lock			ssd_range_lock
1051 #define	sd_get_range			ssd_get_range
1052 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1053 #define	sd_range_unlock			ssd_range_unlock
1054 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1055 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1056 
1057 #define	sd_iostart_chain		ssd_iostart_chain
1058 #define	sd_iodone_chain			ssd_iodone_chain
1059 #define	sd_initpkt_map			ssd_initpkt_map
1060 #define	sd_destroypkt_map		ssd_destroypkt_map
1061 #define	sd_chain_type_map		ssd_chain_type_map
1062 #define	sd_chain_index_map		ssd_chain_index_map
1063 
1064 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1065 #define	sd_failfast_flushq		ssd_failfast_flushq
1066 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1067 
1068 #define	sd_is_lsi			ssd_is_lsi
1069 
1070 #endif	/* #if (defined(__fibre)) */
1071 
1072 
1073 int _init(void);
1074 int _fini(void);
1075 int _info(struct modinfo *modinfop);
1076 
1077 /*PRINTFLIKE3*/
1078 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1079 /*PRINTFLIKE3*/
1080 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1081 /*PRINTFLIKE3*/
1082 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1083 
1084 static int sdprobe(dev_info_t *devi);
1085 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1086     void **result);
1087 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1088     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1089 
1090 /*
1091  * Smart probe for parallel scsi
1092  */
1093 static void sd_scsi_probe_cache_init(void);
1094 static void sd_scsi_probe_cache_fini(void);
1095 static void sd_scsi_clear_probe_cache(void);
1096 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1097 
1098 static int	sd_spin_up_unit(struct sd_lun *un);
1099 #ifdef _LP64
1100 static void	sd_enable_descr_sense(struct sd_lun *un);
1101 #endif /* _LP64 */
1102 static void	sd_set_mmc_caps(struct sd_lun *un);
1103 
1104 static void sd_read_unit_properties(struct sd_lun *un);
1105 static int  sd_process_sdconf_file(struct sd_lun *un);
1106 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1107     int *data_list, sd_tunables *values);
1108 static void sd_process_sdconf_table(struct sd_lun *un);
1109 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1110 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1111 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1112 	int list_len, char *dataname_ptr);
1113 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1114     sd_tunables *prop_list);
1115 static int  sd_validate_geometry(struct sd_lun *un, int path_flag);
1116 
1117 #if defined(_SUNOS_VTOC_16)
1118 static void sd_convert_geometry(uint64_t capacity, struct dk_geom *un_g);
1119 #endif
1120 
1121 static void sd_resync_geom_caches(struct sd_lun *un, int capacity, int lbasize,
1122 	int path_flag);
1123 static int  sd_read_fdisk(struct sd_lun *un, uint_t capacity, int lbasize,
1124 	int path_flag);
1125 static void sd_get_physical_geometry(struct sd_lun *un,
1126 	struct geom_cache *pgeom_p, int capacity, int lbasize, int path_flag);
1127 static void sd_get_virtual_geometry(struct sd_lun *un, int capacity,
1128 	int lbasize);
1129 static int  sd_uselabel(struct sd_lun *un, struct dk_label *l, int path_flag);
1130 static void sd_swap_efi_gpt(efi_gpt_t *);
1131 static void sd_swap_efi_gpe(int nparts, efi_gpe_t *);
1132 static int sd_validate_efi(efi_gpt_t *);
1133 static int sd_use_efi(struct sd_lun *, int);
1134 static void sd_build_default_label(struct sd_lun *un);
1135 
1136 #if defined(_FIRMWARE_NEEDS_FDISK)
1137 static int  sd_has_max_chs_vals(struct ipart *fdp);
1138 #endif
1139 static void sd_inq_fill(char *p, int l, char *s);
1140 
1141 
1142 static void sd_register_devid(struct sd_lun *un, dev_info_t *devi,
1143     int reservation_flag);
1144 static daddr_t  sd_get_devid_block(struct sd_lun *un);
1145 static int  sd_get_devid(struct sd_lun *un);
1146 static int  sd_get_serialnum(struct sd_lun *un, uchar_t *wwn, int *len);
1147 static ddi_devid_t sd_create_devid(struct sd_lun *un);
1148 static int  sd_write_deviceid(struct sd_lun *un);
1149 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1150 static int  sd_check_vpd_page_support(struct sd_lun *un);
1151 
1152 static void sd_setup_pm(struct sd_lun *un, dev_info_t *devi);
1153 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1154 
1155 static int  sd_ddi_suspend(dev_info_t *devi);
1156 static int  sd_ddi_pm_suspend(struct sd_lun *un);
1157 static int  sd_ddi_resume(dev_info_t *devi);
1158 static int  sd_ddi_pm_resume(struct sd_lun *un);
1159 static int  sdpower(dev_info_t *devi, int component, int level);
1160 
1161 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1162 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1163 static int  sd_unit_attach(dev_info_t *devi);
1164 static int  sd_unit_detach(dev_info_t *devi);
1165 
1166 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1167 static int  sd_create_minor_nodes(struct sd_lun *un, dev_info_t *devi);
1168 static void sd_create_errstats(struct sd_lun *un, int instance);
1169 static void sd_set_errstats(struct sd_lun *un);
1170 static void sd_set_pstats(struct sd_lun *un);
1171 
1172 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1173 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1174 static int  sd_send_polled_RQS(struct sd_lun *un);
1175 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1176 
1177 #if (defined(__fibre))
1178 /*
1179  * Event callbacks (photon)
1180  */
1181 static void sd_init_event_callbacks(struct sd_lun *un);
1182 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1183 #endif
1184 
1185 /*
1186  * Defines for sd_cache_control
1187  */
1188 
1189 #define	SD_CACHE_ENABLE		1
1190 #define	SD_CACHE_DISABLE	0
1191 #define	SD_CACHE_NOCHANGE	-1
1192 
1193 static int   sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag);
1194 static int   sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled);
1195 static dev_t sd_make_device(dev_info_t *devi);
1196 
1197 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1198 	uint64_t capacity);
1199 
1200 /*
1201  * Driver entry point functions.
1202  */
1203 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1204 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1205 static int  sd_ready_and_valid(struct sd_lun *un);
1206 
1207 static void sdmin(struct buf *bp);
1208 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1209 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1210 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1211 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1212 
1213 static int sdstrategy(struct buf *bp);
1214 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1215 
1216 /*
1217  * Function prototypes for layering functions in the iostart chain.
1218  */
1219 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1220 	struct buf *bp);
1221 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1222 	struct buf *bp);
1223 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1224 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1225 	struct buf *bp);
1226 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1227 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1228 
1229 /*
1230  * Function prototypes for layering functions in the iodone chain.
1231  */
1232 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1233 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1234 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1235 	struct buf *bp);
1236 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1237 	struct buf *bp);
1238 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1239 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1240 	struct buf *bp);
1241 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1242 
1243 /*
1244  * Prototypes for functions to support buf(9S) based IO.
1245  */
1246 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1247 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1248 static void sd_destroypkt_for_buf(struct buf *);
1249 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1250 	struct buf *bp, int flags,
1251 	int (*callback)(caddr_t), caddr_t callback_arg,
1252 	diskaddr_t lba, uint32_t blockcount);
1253 #if defined(__i386) || defined(__amd64)
1254 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1255 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1256 #endif /* defined(__i386) || defined(__amd64) */
1257 
1258 /*
1259  * Prototypes for functions to support USCSI IO.
1260  */
1261 static int sd_uscsi_strategy(struct buf *bp);
1262 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1263 static void sd_destroypkt_for_uscsi(struct buf *);
1264 
1265 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1266 	uchar_t chain_type, void *pktinfop);
1267 
1268 static int  sd_pm_entry(struct sd_lun *un);
1269 static void sd_pm_exit(struct sd_lun *un);
1270 
1271 static void sd_pm_idletimeout_handler(void *arg);
1272 
1273 /*
1274  * sd_core internal functions (used at the sd_core_io layer).
1275  */
1276 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1277 static void sdintr(struct scsi_pkt *pktp);
1278 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1279 
1280 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd,
1281 	enum uio_seg cdbspace, enum uio_seg dataspace, enum uio_seg rqbufspace,
1282 	int path_flag);
1283 
1284 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1285 	daddr_t blkno, int (*func)(struct buf *));
1286 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1287 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1288 static void sd_bioclone_free(struct buf *bp);
1289 static void sd_shadow_buf_free(struct buf *bp);
1290 
1291 static void sd_print_transport_rejected_message(struct sd_lun *un,
1292 	struct sd_xbuf *xp, int code);
1293 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1294     void *arg, int code);
1295 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1296     void *arg, int code);
1297 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1298     void *arg, int code);
1299 
1300 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1301 	int retry_check_flag,
1302 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1303 		int c),
1304 	void *user_arg, int failure_code,  clock_t retry_delay,
1305 	void (*statp)(kstat_io_t *));
1306 
1307 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1308 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1309 
1310 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1311 	struct scsi_pkt *pktp);
1312 static void sd_start_retry_command(void *arg);
1313 static void sd_start_direct_priority_command(void *arg);
1314 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1315 	int errcode);
1316 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1317 	struct buf *bp, int errcode);
1318 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1319 static void sd_sync_with_callback(struct sd_lun *un);
1320 static int sdrunout(caddr_t arg);
1321 
1322 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1323 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1324 
1325 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1326 static void sd_restore_throttle(void *arg);
1327 
1328 static void sd_init_cdb_limits(struct sd_lun *un);
1329 
1330 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1331 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1332 
1333 /*
1334  * Error handling functions
1335  */
1336 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1337 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1338 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1339 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1340 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1341 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1342 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1343 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1344 
1345 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1346 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1347 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1348 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1349 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1350 	struct sd_xbuf *xp);
1351 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1352 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1353 
1354 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1355 	void *arg, int code);
1356 static diskaddr_t sd_extract_sense_info_descr(
1357 	struct scsi_descr_sense_hdr *sdsp);
1358 
1359 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1360 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1361 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1362 	uint8_t asc,
1363 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1364 static void sd_sense_key_not_ready(struct sd_lun *un,
1365 	uint8_t asc, uint8_t ascq,
1366 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1367 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1368 	int sense_key, uint8_t asc,
1369 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1370 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1371 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1372 static void sd_sense_key_unit_attention(struct sd_lun *un,
1373 	uint8_t asc,
1374 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1375 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1376 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1377 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1378 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1379 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1380 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1381 static void sd_sense_key_default(struct sd_lun *un,
1382 	int sense_key,
1383 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1384 
1385 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1386 	void *arg, int flag);
1387 
1388 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1389 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1390 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1391 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1392 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1393 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1394 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1395 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1396 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1397 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1398 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1399 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1400 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1401 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1402 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1403 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1404 
1405 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1406 
1407 static void sd_start_stop_unit_callback(void *arg);
1408 static void sd_start_stop_unit_task(void *arg);
1409 
1410 static void sd_taskq_create(void);
1411 static void sd_taskq_delete(void);
1412 static void sd_media_change_task(void *arg);
1413 
1414 static int sd_handle_mchange(struct sd_lun *un);
1415 static int sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag);
1416 static int sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp,
1417 	uint32_t *lbap, int path_flag);
1418 static int sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
1419 	uint32_t *lbap, int path_flag);
1420 static int sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag,
1421 	int path_flag);
1422 static int sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr,
1423 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1424 static int sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag);
1425 static int sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un,
1426 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1427 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un,
1428 	uchar_t usr_cmd, uchar_t *usr_bufp);
1429 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1430 	struct dk_callback *dkc);
1431 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1432 static int sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un,
1433 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1434 	uchar_t *bufaddr, uint_t buflen);
1435 static int sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
1436 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1437 	uchar_t *bufaddr, uint_t buflen, char feature);
1438 static int sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize,
1439 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1440 static int sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize,
1441 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1442 static int sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
1443 	size_t buflen, daddr_t start_block, int path_flag);
1444 #define	sd_send_scsi_READ(un, bufaddr, buflen, start_block, path_flag)	\
1445 	sd_send_scsi_RDWR(un, SCMD_READ, bufaddr, buflen, start_block, \
1446 	path_flag)
1447 #define	sd_send_scsi_WRITE(un, bufaddr, buflen, start_block, path_flag)	\
1448 	sd_send_scsi_RDWR(un, SCMD_WRITE, bufaddr, buflen, start_block,\
1449 	path_flag)
1450 
1451 static int sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr,
1452 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1453 	uint16_t param_ptr, int path_flag);
1454 
1455 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1456 static void sd_free_rqs(struct sd_lun *un);
1457 
1458 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1459 	uchar_t *data, int len, int fmt);
1460 static void sd_panic_for_res_conflict(struct sd_lun *un);
1461 
1462 /*
1463  * Disk Ioctl Function Prototypes
1464  */
1465 static int sd_uscsi_ioctl(dev_t dev, caddr_t arg, int flag);
1466 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1467 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1468 static int sd_dkio_get_geometry(dev_t dev, caddr_t arg, int flag,
1469 	int geom_validated);
1470 static int sd_dkio_set_geometry(dev_t dev, caddr_t arg, int flag);
1471 static int sd_dkio_get_partition(dev_t dev, caddr_t arg, int flag,
1472 	int geom_validated);
1473 static int sd_dkio_set_partition(dev_t dev, caddr_t arg, int flag);
1474 static int sd_dkio_get_vtoc(dev_t dev, caddr_t arg, int flag,
1475 	int geom_validated);
1476 static int sd_dkio_get_efi(dev_t dev, caddr_t arg, int flag);
1477 static int sd_dkio_partition(dev_t dev, caddr_t arg, int flag);
1478 static void sd_build_user_vtoc(struct sd_lun *un, struct vtoc *user_vtoc);
1479 static int sd_dkio_set_vtoc(dev_t dev, caddr_t arg, int flag);
1480 static int sd_dkio_set_efi(dev_t dev, caddr_t arg, int flag);
1481 static int sd_build_label_vtoc(struct sd_lun *un, struct vtoc *user_vtoc);
1482 static int sd_write_label(dev_t dev);
1483 static int sd_set_vtoc(struct sd_lun *un, struct dk_label *dkl);
1484 static void sd_clear_vtoc(struct sd_lun *un);
1485 static void sd_clear_efi(struct sd_lun *un);
1486 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1487 static int sd_dkio_get_mboot(dev_t dev, caddr_t arg, int flag);
1488 static int sd_dkio_set_mboot(dev_t dev, caddr_t arg, int flag);
1489 static void sd_setup_default_geometry(struct sd_lun *un);
1490 #if defined(__i386) || defined(__amd64)
1491 static int sd_update_fdisk_and_vtoc(struct sd_lun *un);
1492 #endif
1493 
1494 /*
1495  * Multi-host Ioctl Prototypes
1496  */
1497 static int sd_check_mhd(dev_t dev, int interval);
1498 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1499 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1500 static char *sd_sname(uchar_t status);
1501 static void sd_mhd_resvd_recover(void *arg);
1502 static void sd_resv_reclaim_thread();
1503 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1504 static int sd_reserve_release(dev_t dev, int cmd);
1505 static void sd_rmv_resv_reclaim_req(dev_t dev);
1506 static void sd_mhd_reset_notify_cb(caddr_t arg);
1507 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1508 	mhioc_inkeys_t *usrp, int flag);
1509 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1510 	mhioc_inresvs_t *usrp, int flag);
1511 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1512 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1513 static int sd_mhdioc_release(dev_t dev);
1514 static int sd_mhdioc_register_devid(dev_t dev);
1515 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1516 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1517 
1518 /*
1519  * SCSI removable prototypes
1520  */
1521 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1522 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1523 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1524 static int sr_pause_resume(dev_t dev, int mode);
1525 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1526 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1527 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1528 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1529 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1530 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1531 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1532 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1533 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1534 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1535 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1536 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1537 static int sr_eject(dev_t dev);
1538 static void sr_ejected(register struct sd_lun *un);
1539 static int sr_check_wp(dev_t dev);
1540 static int sd_check_media(dev_t dev, enum dkio_state state);
1541 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1542 static void sd_delayed_cv_broadcast(void *arg);
1543 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1544 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1545 
1546 static int sd_log_page_supported(struct sd_lun *un, int log_page);
1547 
1548 /*
1549  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1550  */
1551 static void sd_check_for_writable_cd(struct sd_lun *un);
1552 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1553 static void sd_wm_cache_destructor(void *wm, void *un);
1554 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1555 	daddr_t endb, ushort_t typ);
1556 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1557 	daddr_t endb);
1558 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1559 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1560 static void sd_read_modify_write_task(void * arg);
1561 static int
1562 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1563 	struct buf **bpp);
1564 
1565 
1566 /*
1567  * Function prototypes for failfast support.
1568  */
1569 static void sd_failfast_flushq(struct sd_lun *un);
1570 static int sd_failfast_flushq_callback(struct buf *bp);
1571 
1572 /*
1573  * Function prototypes to check for lsi devices
1574  */
1575 static void sd_is_lsi(struct sd_lun *un);
1576 
1577 /*
1578  * Function prototypes for x86 support
1579  */
1580 #if defined(__i386) || defined(__amd64)
1581 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1582 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1583 #endif
1584 
1585 /*
1586  * Constants for failfast support:
1587  *
1588  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1589  * failfast processing being performed.
1590  *
1591  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1592  * failfast processing on all bufs with B_FAILFAST set.
1593  */
1594 
1595 #define	SD_FAILFAST_INACTIVE		0
1596 #define	SD_FAILFAST_ACTIVE		1
1597 
1598 /*
1599  * Bitmask to control behavior of buf(9S) flushes when a transition to
1600  * the failfast state occurs. Optional bits include:
1601  *
1602  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1603  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1604  * be flushed.
1605  *
1606  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1607  * driver, in addition to the regular wait queue. This includes the xbuf
1608  * queues. When clear, only the driver's wait queue will be flushed.
1609  */
1610 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1611 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1612 
1613 /*
1614  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1615  * to flush all queues within the driver.
1616  */
1617 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1618 
1619 
1620 /*
1621  * SD Testing Fault Injection
1622  */
1623 #ifdef SD_FAULT_INJECTION
1624 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1625 static void sd_faultinjection(struct scsi_pkt *pktp);
1626 static void sd_injection_log(char *buf, struct sd_lun *un);
1627 #endif
1628 
1629 /*
1630  * Device driver ops vector
1631  */
1632 static struct cb_ops sd_cb_ops = {
1633 	sdopen,			/* open */
1634 	sdclose,		/* close */
1635 	sdstrategy,		/* strategy */
1636 	nodev,			/* print */
1637 	sddump,			/* dump */
1638 	sdread,			/* read */
1639 	sdwrite,		/* write */
1640 	sdioctl,		/* ioctl */
1641 	nodev,			/* devmap */
1642 	nodev,			/* mmap */
1643 	nodev,			/* segmap */
1644 	nochpoll,		/* poll */
1645 	sd_prop_op,		/* cb_prop_op */
1646 	0,			/* streamtab  */
1647 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1648 	CB_REV,			/* cb_rev */
1649 	sdaread, 		/* async I/O read entry point */
1650 	sdawrite		/* async I/O write entry point */
1651 };
1652 
1653 static struct dev_ops sd_ops = {
1654 	DEVO_REV,		/* devo_rev, */
1655 	0,			/* refcnt  */
1656 	sdinfo,			/* info */
1657 	nulldev,		/* identify */
1658 	sdprobe,		/* probe */
1659 	sdattach,		/* attach */
1660 	sddetach,		/* detach */
1661 	nodev,			/* reset */
1662 	&sd_cb_ops,		/* driver operations */
1663 	NULL,			/* bus operations */
1664 	sdpower			/* power */
1665 };
1666 
1667 
1668 /*
1669  * This is the loadable module wrapper.
1670  */
1671 #include <sys/modctl.h>
1672 
1673 static struct modldrv modldrv = {
1674 	&mod_driverops,		/* Type of module. This one is a driver */
1675 	SD_MODULE_NAME,		/* Module name. */
1676 	&sd_ops			/* driver ops */
1677 };
1678 
1679 
1680 static struct modlinkage modlinkage = {
1681 	MODREV_1,
1682 	&modldrv,
1683 	NULL
1684 };
1685 
1686 
1687 static struct scsi_asq_key_strings sd_additional_codes[] = {
1688 	0x81, 0, "Logical Unit is Reserved",
1689 	0x85, 0, "Audio Address Not Valid",
1690 	0xb6, 0, "Media Load Mechanism Failed",
1691 	0xB9, 0, "Audio Play Operation Aborted",
1692 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1693 	0x53, 2, "Medium removal prevented",
1694 	0x6f, 0, "Authentication failed during key exchange",
1695 	0x6f, 1, "Key not present",
1696 	0x6f, 2, "Key not established",
1697 	0x6f, 3, "Read without proper authentication",
1698 	0x6f, 4, "Mismatched region to this logical unit",
1699 	0x6f, 5, "Region reset count error",
1700 	0xffff, 0x0, NULL
1701 };
1702 
1703 
1704 /*
1705  * Struct for passing printing information for sense data messages
1706  */
1707 struct sd_sense_info {
1708 	int	ssi_severity;
1709 	int	ssi_pfa_flag;
1710 };
1711 
1712 /*
1713  * Table of function pointers for iostart-side routines. Seperate "chains"
1714  * of layered function calls are formed by placing the function pointers
1715  * sequentially in the desired order. Functions are called according to an
1716  * incrementing table index ordering. The last function in each chain must
1717  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1718  * in the sd_iodone_chain[] array.
1719  *
1720  * Note: It may seem more natural to organize both the iostart and iodone
1721  * functions together, into an array of structures (or some similar
1722  * organization) with a common index, rather than two seperate arrays which
1723  * must be maintained in synchronization. The purpose of this division is
1724  * to achiece improved performance: individual arrays allows for more
1725  * effective cache line utilization on certain platforms.
1726  */
1727 
1728 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1729 
1730 
1731 static sd_chain_t sd_iostart_chain[] = {
1732 
1733 	/* Chain for buf IO for disk drive targets (PM enabled) */
1734 	sd_mapblockaddr_iostart,	/* Index: 0 */
1735 	sd_pm_iostart,			/* Index: 1 */
1736 	sd_core_iostart,		/* Index: 2 */
1737 
1738 	/* Chain for buf IO for disk drive targets (PM disabled) */
1739 	sd_mapblockaddr_iostart,	/* Index: 3 */
1740 	sd_core_iostart,		/* Index: 4 */
1741 
1742 	/* Chain for buf IO for removable-media targets (PM enabled) */
1743 	sd_mapblockaddr_iostart,	/* Index: 5 */
1744 	sd_mapblocksize_iostart,	/* Index: 6 */
1745 	sd_pm_iostart,			/* Index: 7 */
1746 	sd_core_iostart,		/* Index: 8 */
1747 
1748 	/* Chain for buf IO for removable-media targets (PM disabled) */
1749 	sd_mapblockaddr_iostart,	/* Index: 9 */
1750 	sd_mapblocksize_iostart,	/* Index: 10 */
1751 	sd_core_iostart,		/* Index: 11 */
1752 
1753 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1754 	sd_mapblockaddr_iostart,	/* Index: 12 */
1755 	sd_checksum_iostart,		/* Index: 13 */
1756 	sd_pm_iostart,			/* Index: 14 */
1757 	sd_core_iostart,		/* Index: 15 */
1758 
1759 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1760 	sd_mapblockaddr_iostart,	/* Index: 16 */
1761 	sd_checksum_iostart,		/* Index: 17 */
1762 	sd_core_iostart,		/* Index: 18 */
1763 
1764 	/* Chain for USCSI commands (all targets) */
1765 	sd_pm_iostart,			/* Index: 19 */
1766 	sd_core_iostart,		/* Index: 20 */
1767 
1768 	/* Chain for checksumming USCSI commands (all targets) */
1769 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1770 	sd_pm_iostart,			/* Index: 22 */
1771 	sd_core_iostart,		/* Index: 23 */
1772 
1773 	/* Chain for "direct" USCSI commands (all targets) */
1774 	sd_core_iostart,		/* Index: 24 */
1775 
1776 	/* Chain for "direct priority" USCSI commands (all targets) */
1777 	sd_core_iostart,		/* Index: 25 */
1778 };
1779 
1780 /*
1781  * Macros to locate the first function of each iostart chain in the
1782  * sd_iostart_chain[] array. These are located by the index in the array.
1783  */
1784 #define	SD_CHAIN_DISK_IOSTART			0
1785 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1786 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1787 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1788 #define	SD_CHAIN_CHKSUM_IOSTART			12
1789 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1790 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1791 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1792 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1793 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1794 
1795 
1796 /*
1797  * Table of function pointers for the iodone-side routines for the driver-
1798  * internal layering mechanism.  The calling sequence for iodone routines
1799  * uses a decrementing table index, so the last routine called in a chain
1800  * must be at the lowest array index location for that chain.  The last
1801  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1802  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1803  * of the functions in an iodone side chain must correspond to the ordering
1804  * of the iostart routines for that chain.  Note that there is no iodone
1805  * side routine that corresponds to sd_core_iostart(), so there is no
1806  * entry in the table for this.
1807  */
1808 
1809 static sd_chain_t sd_iodone_chain[] = {
1810 
1811 	/* Chain for buf IO for disk drive targets (PM enabled) */
1812 	sd_buf_iodone,			/* Index: 0 */
1813 	sd_mapblockaddr_iodone,		/* Index: 1 */
1814 	sd_pm_iodone,			/* Index: 2 */
1815 
1816 	/* Chain for buf IO for disk drive targets (PM disabled) */
1817 	sd_buf_iodone,			/* Index: 3 */
1818 	sd_mapblockaddr_iodone,		/* Index: 4 */
1819 
1820 	/* Chain for buf IO for removable-media targets (PM enabled) */
1821 	sd_buf_iodone,			/* Index: 5 */
1822 	sd_mapblockaddr_iodone,		/* Index: 6 */
1823 	sd_mapblocksize_iodone,		/* Index: 7 */
1824 	sd_pm_iodone,			/* Index: 8 */
1825 
1826 	/* Chain for buf IO for removable-media targets (PM disabled) */
1827 	sd_buf_iodone,			/* Index: 9 */
1828 	sd_mapblockaddr_iodone,		/* Index: 10 */
1829 	sd_mapblocksize_iodone,		/* Index: 11 */
1830 
1831 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1832 	sd_buf_iodone,			/* Index: 12 */
1833 	sd_mapblockaddr_iodone,		/* Index: 13 */
1834 	sd_checksum_iodone,		/* Index: 14 */
1835 	sd_pm_iodone,			/* Index: 15 */
1836 
1837 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1838 	sd_buf_iodone,			/* Index: 16 */
1839 	sd_mapblockaddr_iodone,		/* Index: 17 */
1840 	sd_checksum_iodone,		/* Index: 18 */
1841 
1842 	/* Chain for USCSI commands (non-checksum targets) */
1843 	sd_uscsi_iodone,		/* Index: 19 */
1844 	sd_pm_iodone,			/* Index: 20 */
1845 
1846 	/* Chain for USCSI commands (checksum targets) */
1847 	sd_uscsi_iodone,		/* Index: 21 */
1848 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1849 	sd_pm_iodone,			/* Index: 22 */
1850 
1851 	/* Chain for "direct" USCSI commands (all targets) */
1852 	sd_uscsi_iodone,		/* Index: 24 */
1853 
1854 	/* Chain for "direct priority" USCSI commands (all targets) */
1855 	sd_uscsi_iodone,		/* Index: 25 */
1856 };
1857 
1858 
1859 /*
1860  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1861  * each iodone-side chain. These are located by the array index, but as the
1862  * iodone side functions are called in a decrementing-index order, the
1863  * highest index number in each chain must be specified (as these correspond
1864  * to the first function in the iodone chain that will be called by the core
1865  * at IO completion time).
1866  */
1867 
1868 #define	SD_CHAIN_DISK_IODONE			2
1869 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1870 #define	SD_CHAIN_RMMEDIA_IODONE			8
1871 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1872 #define	SD_CHAIN_CHKSUM_IODONE			15
1873 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1874 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1875 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1876 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1877 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1878 
1879 
1880 
1881 
1882 /*
1883  * Array to map a layering chain index to the appropriate initpkt routine.
1884  * The redundant entries are present so that the index used for accessing
1885  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1886  * with this table as well.
1887  */
1888 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1889 
1890 static sd_initpkt_t	sd_initpkt_map[] = {
1891 
1892 	/* Chain for buf IO for disk drive targets (PM enabled) */
1893 	sd_initpkt_for_buf,		/* Index: 0 */
1894 	sd_initpkt_for_buf,		/* Index: 1 */
1895 	sd_initpkt_for_buf,		/* Index: 2 */
1896 
1897 	/* Chain for buf IO for disk drive targets (PM disabled) */
1898 	sd_initpkt_for_buf,		/* Index: 3 */
1899 	sd_initpkt_for_buf,		/* Index: 4 */
1900 
1901 	/* Chain for buf IO for removable-media targets (PM enabled) */
1902 	sd_initpkt_for_buf,		/* Index: 5 */
1903 	sd_initpkt_for_buf,		/* Index: 6 */
1904 	sd_initpkt_for_buf,		/* Index: 7 */
1905 	sd_initpkt_for_buf,		/* Index: 8 */
1906 
1907 	/* Chain for buf IO for removable-media targets (PM disabled) */
1908 	sd_initpkt_for_buf,		/* Index: 9 */
1909 	sd_initpkt_for_buf,		/* Index: 10 */
1910 	sd_initpkt_for_buf,		/* Index: 11 */
1911 
1912 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1913 	sd_initpkt_for_buf,		/* Index: 12 */
1914 	sd_initpkt_for_buf,		/* Index: 13 */
1915 	sd_initpkt_for_buf,		/* Index: 14 */
1916 	sd_initpkt_for_buf,		/* Index: 15 */
1917 
1918 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1919 	sd_initpkt_for_buf,		/* Index: 16 */
1920 	sd_initpkt_for_buf,		/* Index: 17 */
1921 	sd_initpkt_for_buf,		/* Index: 18 */
1922 
1923 	/* Chain for USCSI commands (non-checksum targets) */
1924 	sd_initpkt_for_uscsi,		/* Index: 19 */
1925 	sd_initpkt_for_uscsi,		/* Index: 20 */
1926 
1927 	/* Chain for USCSI commands (checksum targets) */
1928 	sd_initpkt_for_uscsi,		/* Index: 21 */
1929 	sd_initpkt_for_uscsi,		/* Index: 22 */
1930 	sd_initpkt_for_uscsi,		/* Index: 22 */
1931 
1932 	/* Chain for "direct" USCSI commands (all targets) */
1933 	sd_initpkt_for_uscsi,		/* Index: 24 */
1934 
1935 	/* Chain for "direct priority" USCSI commands (all targets) */
1936 	sd_initpkt_for_uscsi,		/* Index: 25 */
1937 
1938 };
1939 
1940 
1941 /*
1942  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1943  * The redundant entries are present so that the index used for accessing
1944  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1945  * with this table as well.
1946  */
1947 typedef void (*sd_destroypkt_t)(struct buf *);
1948 
1949 static sd_destroypkt_t	sd_destroypkt_map[] = {
1950 
1951 	/* Chain for buf IO for disk drive targets (PM enabled) */
1952 	sd_destroypkt_for_buf,		/* Index: 0 */
1953 	sd_destroypkt_for_buf,		/* Index: 1 */
1954 	sd_destroypkt_for_buf,		/* Index: 2 */
1955 
1956 	/* Chain for buf IO for disk drive targets (PM disabled) */
1957 	sd_destroypkt_for_buf,		/* Index: 3 */
1958 	sd_destroypkt_for_buf,		/* Index: 4 */
1959 
1960 	/* Chain for buf IO for removable-media targets (PM enabled) */
1961 	sd_destroypkt_for_buf,		/* Index: 5 */
1962 	sd_destroypkt_for_buf,		/* Index: 6 */
1963 	sd_destroypkt_for_buf,		/* Index: 7 */
1964 	sd_destroypkt_for_buf,		/* Index: 8 */
1965 
1966 	/* Chain for buf IO for removable-media targets (PM disabled) */
1967 	sd_destroypkt_for_buf,		/* Index: 9 */
1968 	sd_destroypkt_for_buf,		/* Index: 10 */
1969 	sd_destroypkt_for_buf,		/* Index: 11 */
1970 
1971 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1972 	sd_destroypkt_for_buf,		/* Index: 12 */
1973 	sd_destroypkt_for_buf,		/* Index: 13 */
1974 	sd_destroypkt_for_buf,		/* Index: 14 */
1975 	sd_destroypkt_for_buf,		/* Index: 15 */
1976 
1977 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1978 	sd_destroypkt_for_buf,		/* Index: 16 */
1979 	sd_destroypkt_for_buf,		/* Index: 17 */
1980 	sd_destroypkt_for_buf,		/* Index: 18 */
1981 
1982 	/* Chain for USCSI commands (non-checksum targets) */
1983 	sd_destroypkt_for_uscsi,	/* Index: 19 */
1984 	sd_destroypkt_for_uscsi,	/* Index: 20 */
1985 
1986 	/* Chain for USCSI commands (checksum targets) */
1987 	sd_destroypkt_for_uscsi,	/* Index: 21 */
1988 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1989 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1990 
1991 	/* Chain for "direct" USCSI commands (all targets) */
1992 	sd_destroypkt_for_uscsi,	/* Index: 24 */
1993 
1994 	/* Chain for "direct priority" USCSI commands (all targets) */
1995 	sd_destroypkt_for_uscsi,	/* Index: 25 */
1996 
1997 };
1998 
1999 
2000 
2001 /*
2002  * Array to map a layering chain index to the appropriate chain "type".
2003  * The chain type indicates a specific property/usage of the chain.
2004  * The redundant entries are present so that the index used for accessing
2005  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2006  * with this table as well.
2007  */
2008 
2009 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2010 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2011 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2012 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2013 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2014 						/* (for error recovery) */
2015 
2016 static int sd_chain_type_map[] = {
2017 
2018 	/* Chain for buf IO for disk drive targets (PM enabled) */
2019 	SD_CHAIN_BUFIO,			/* Index: 0 */
2020 	SD_CHAIN_BUFIO,			/* Index: 1 */
2021 	SD_CHAIN_BUFIO,			/* Index: 2 */
2022 
2023 	/* Chain for buf IO for disk drive targets (PM disabled) */
2024 	SD_CHAIN_BUFIO,			/* Index: 3 */
2025 	SD_CHAIN_BUFIO,			/* Index: 4 */
2026 
2027 	/* Chain for buf IO for removable-media targets (PM enabled) */
2028 	SD_CHAIN_BUFIO,			/* Index: 5 */
2029 	SD_CHAIN_BUFIO,			/* Index: 6 */
2030 	SD_CHAIN_BUFIO,			/* Index: 7 */
2031 	SD_CHAIN_BUFIO,			/* Index: 8 */
2032 
2033 	/* Chain for buf IO for removable-media targets (PM disabled) */
2034 	SD_CHAIN_BUFIO,			/* Index: 9 */
2035 	SD_CHAIN_BUFIO,			/* Index: 10 */
2036 	SD_CHAIN_BUFIO,			/* Index: 11 */
2037 
2038 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2039 	SD_CHAIN_BUFIO,			/* Index: 12 */
2040 	SD_CHAIN_BUFIO,			/* Index: 13 */
2041 	SD_CHAIN_BUFIO,			/* Index: 14 */
2042 	SD_CHAIN_BUFIO,			/* Index: 15 */
2043 
2044 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2045 	SD_CHAIN_BUFIO,			/* Index: 16 */
2046 	SD_CHAIN_BUFIO,			/* Index: 17 */
2047 	SD_CHAIN_BUFIO,			/* Index: 18 */
2048 
2049 	/* Chain for USCSI commands (non-checksum targets) */
2050 	SD_CHAIN_USCSI,			/* Index: 19 */
2051 	SD_CHAIN_USCSI,			/* Index: 20 */
2052 
2053 	/* Chain for USCSI commands (checksum targets) */
2054 	SD_CHAIN_USCSI,			/* Index: 21 */
2055 	SD_CHAIN_USCSI,			/* Index: 22 */
2056 	SD_CHAIN_USCSI,			/* Index: 22 */
2057 
2058 	/* Chain for "direct" USCSI commands (all targets) */
2059 	SD_CHAIN_DIRECT,		/* Index: 24 */
2060 
2061 	/* Chain for "direct priority" USCSI commands (all targets) */
2062 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2063 };
2064 
2065 
2066 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2067 #define	SD_IS_BUFIO(xp)			\
2068 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2069 
2070 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2071 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2072 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2073 
2074 
2075 
2076 /*
2077  * Struct, array, and macros to map a specific chain to the appropriate
2078  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2079  *
2080  * The sd_chain_index_map[] array is used at attach time to set the various
2081  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2082  * chain to be used with the instance. This allows different instances to use
2083  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2084  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2085  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2086  * dynamically & without the use of locking; and (2) a layer may update the
2087  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2088  * to allow for deferred processing of an IO within the same chain from a
2089  * different execution context.
2090  */
2091 
2092 struct sd_chain_index {
2093 	int	sci_iostart_index;
2094 	int	sci_iodone_index;
2095 };
2096 
2097 static struct sd_chain_index	sd_chain_index_map[] = {
2098 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2099 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2100 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2101 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2102 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2103 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2104 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2105 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2106 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2107 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2108 };
2109 
2110 
2111 /*
2112  * The following are indexes into the sd_chain_index_map[] array.
2113  */
2114 
2115 /* un->un_buf_chain_type must be set to one of these */
2116 #define	SD_CHAIN_INFO_DISK		0
2117 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2118 #define	SD_CHAIN_INFO_RMMEDIA		2
2119 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2120 #define	SD_CHAIN_INFO_CHKSUM		4
2121 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2122 
2123 /* un->un_uscsi_chain_type must be set to one of these */
2124 #define	SD_CHAIN_INFO_USCSI_CMD		6
2125 /* USCSI with PM disabled is the same as DIRECT */
2126 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2127 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2128 
2129 /* un->un_direct_chain_type must be set to one of these */
2130 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2131 
2132 /* un->un_priority_chain_type must be set to one of these */
2133 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2134 
2135 /* size for devid inquiries */
2136 #define	MAX_INQUIRY_SIZE		0xF0
2137 
2138 /*
2139  * Macros used by functions to pass a given buf(9S) struct along to the
2140  * next function in the layering chain for further processing.
2141  *
2142  * In the following macros, passing more than three arguments to the called
2143  * routines causes the optimizer for the SPARC compiler to stop doing tail
2144  * call elimination which results in significant performance degradation.
2145  */
2146 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2147 	((*(sd_iostart_chain[index]))(index, un, bp))
2148 
2149 #define	SD_BEGIN_IODONE(index, un, bp)	\
2150 	((*(sd_iodone_chain[index]))(index, un, bp))
2151 
2152 #define	SD_NEXT_IOSTART(index, un, bp)				\
2153 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2154 
2155 #define	SD_NEXT_IODONE(index, un, bp)				\
2156 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2157 
2158 /*
2159  *    Function: _init
2160  *
2161  * Description: This is the driver _init(9E) entry point.
2162  *
2163  * Return Code: Returns the value from mod_install(9F) or
2164  *		ddi_soft_state_init(9F) as appropriate.
2165  *
2166  *     Context: Called when driver module loaded.
2167  */
2168 
2169 int
2170 _init(void)
2171 {
2172 	int	err;
2173 
2174 	/* establish driver name from module name */
2175 	sd_label = mod_modname(&modlinkage);
2176 
2177 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2178 		SD_MAXUNIT);
2179 
2180 	if (err != 0) {
2181 		return (err);
2182 	}
2183 
2184 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2185 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2186 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2187 
2188 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2189 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2190 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2191 
2192 	/*
2193 	 * it's ok to init here even for fibre device
2194 	 */
2195 	sd_scsi_probe_cache_init();
2196 
2197 	/*
2198 	 * Creating taskq before mod_install ensures that all callers (threads)
2199 	 * that enter the module after a successfull mod_install encounter
2200 	 * a valid taskq.
2201 	 */
2202 	sd_taskq_create();
2203 
2204 	err = mod_install(&modlinkage);
2205 	if (err != 0) {
2206 		/* delete taskq if install fails */
2207 		sd_taskq_delete();
2208 
2209 		mutex_destroy(&sd_detach_mutex);
2210 		mutex_destroy(&sd_log_mutex);
2211 		mutex_destroy(&sd_label_mutex);
2212 
2213 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2214 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2215 		cv_destroy(&sd_tr.srq_inprocess_cv);
2216 
2217 		sd_scsi_probe_cache_fini();
2218 
2219 		ddi_soft_state_fini(&sd_state);
2220 		return (err);
2221 	}
2222 
2223 	return (err);
2224 }
2225 
2226 
2227 /*
2228  *    Function: _fini
2229  *
2230  * Description: This is the driver _fini(9E) entry point.
2231  *
2232  * Return Code: Returns the value from mod_remove(9F)
2233  *
2234  *     Context: Called when driver module is unloaded.
2235  */
2236 
2237 int
2238 _fini(void)
2239 {
2240 	int err;
2241 
2242 	if ((err = mod_remove(&modlinkage)) != 0) {
2243 		return (err);
2244 	}
2245 
2246 	sd_taskq_delete();
2247 
2248 	mutex_destroy(&sd_detach_mutex);
2249 	mutex_destroy(&sd_log_mutex);
2250 	mutex_destroy(&sd_label_mutex);
2251 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2252 
2253 	sd_scsi_probe_cache_fini();
2254 
2255 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2256 	cv_destroy(&sd_tr.srq_inprocess_cv);
2257 
2258 	ddi_soft_state_fini(&sd_state);
2259 
2260 	return (err);
2261 }
2262 
2263 
2264 /*
2265  *    Function: _info
2266  *
2267  * Description: This is the driver _info(9E) entry point.
2268  *
2269  *   Arguments: modinfop - pointer to the driver modinfo structure
2270  *
2271  * Return Code: Returns the value from mod_info(9F).
2272  *
2273  *     Context: Kernel thread context
2274  */
2275 
2276 int
2277 _info(struct modinfo *modinfop)
2278 {
2279 	return (mod_info(&modlinkage, modinfop));
2280 }
2281 
2282 
2283 /*
2284  * The following routines implement the driver message logging facility.
2285  * They provide component- and level- based debug output filtering.
2286  * Output may also be restricted to messages for a single instance by
2287  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2288  * to NULL, then messages for all instances are printed.
2289  *
2290  * These routines have been cloned from each other due to the language
2291  * constraints of macros and variable argument list processing.
2292  */
2293 
2294 
2295 /*
2296  *    Function: sd_log_err
2297  *
2298  * Description: This routine is called by the SD_ERROR macro for debug
2299  *		logging of error conditions.
2300  *
2301  *   Arguments: comp - driver component being logged
2302  *		dev  - pointer to driver info structure
2303  *		fmt  - error string and format to be logged
2304  */
2305 
2306 static void
2307 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2308 {
2309 	va_list		ap;
2310 	dev_info_t	*dev;
2311 
2312 	ASSERT(un != NULL);
2313 	dev = SD_DEVINFO(un);
2314 	ASSERT(dev != NULL);
2315 
2316 	/*
2317 	 * Filter messages based on the global component and level masks.
2318 	 * Also print if un matches the value of sd_debug_un, or if
2319 	 * sd_debug_un is set to NULL.
2320 	 */
2321 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2322 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2323 		mutex_enter(&sd_log_mutex);
2324 		va_start(ap, fmt);
2325 		(void) vsprintf(sd_log_buf, fmt, ap);
2326 		va_end(ap);
2327 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2328 		mutex_exit(&sd_log_mutex);
2329 	}
2330 #ifdef SD_FAULT_INJECTION
2331 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2332 	if (un->sd_injection_mask & comp) {
2333 		mutex_enter(&sd_log_mutex);
2334 		va_start(ap, fmt);
2335 		(void) vsprintf(sd_log_buf, fmt, ap);
2336 		va_end(ap);
2337 		sd_injection_log(sd_log_buf, un);
2338 		mutex_exit(&sd_log_mutex);
2339 	}
2340 #endif
2341 }
2342 
2343 
2344 /*
2345  *    Function: sd_log_info
2346  *
2347  * Description: This routine is called by the SD_INFO macro for debug
2348  *		logging of general purpose informational conditions.
2349  *
2350  *   Arguments: comp - driver component being logged
2351  *		dev  - pointer to driver info structure
2352  *		fmt  - info string and format to be logged
2353  */
2354 
2355 static void
2356 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2357 {
2358 	va_list		ap;
2359 	dev_info_t	*dev;
2360 
2361 	ASSERT(un != NULL);
2362 	dev = SD_DEVINFO(un);
2363 	ASSERT(dev != NULL);
2364 
2365 	/*
2366 	 * Filter messages based on the global component and level masks.
2367 	 * Also print if un matches the value of sd_debug_un, or if
2368 	 * sd_debug_un is set to NULL.
2369 	 */
2370 	if ((sd_component_mask & component) &&
2371 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2372 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2373 		mutex_enter(&sd_log_mutex);
2374 		va_start(ap, fmt);
2375 		(void) vsprintf(sd_log_buf, fmt, ap);
2376 		va_end(ap);
2377 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2378 		mutex_exit(&sd_log_mutex);
2379 	}
2380 #ifdef SD_FAULT_INJECTION
2381 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2382 	if (un->sd_injection_mask & component) {
2383 		mutex_enter(&sd_log_mutex);
2384 		va_start(ap, fmt);
2385 		(void) vsprintf(sd_log_buf, fmt, ap);
2386 		va_end(ap);
2387 		sd_injection_log(sd_log_buf, un);
2388 		mutex_exit(&sd_log_mutex);
2389 	}
2390 #endif
2391 }
2392 
2393 
2394 /*
2395  *    Function: sd_log_trace
2396  *
2397  * Description: This routine is called by the SD_TRACE macro for debug
2398  *		logging of trace conditions (i.e. function entry/exit).
2399  *
2400  *   Arguments: comp - driver component being logged
2401  *		dev  - pointer to driver info structure
2402  *		fmt  - trace string and format to be logged
2403  */
2404 
2405 static void
2406 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2407 {
2408 	va_list		ap;
2409 	dev_info_t	*dev;
2410 
2411 	ASSERT(un != NULL);
2412 	dev = SD_DEVINFO(un);
2413 	ASSERT(dev != NULL);
2414 
2415 	/*
2416 	 * Filter messages based on the global component and level masks.
2417 	 * Also print if un matches the value of sd_debug_un, or if
2418 	 * sd_debug_un is set to NULL.
2419 	 */
2420 	if ((sd_component_mask & component) &&
2421 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2422 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2423 		mutex_enter(&sd_log_mutex);
2424 		va_start(ap, fmt);
2425 		(void) vsprintf(sd_log_buf, fmt, ap);
2426 		va_end(ap);
2427 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2428 		mutex_exit(&sd_log_mutex);
2429 	}
2430 #ifdef SD_FAULT_INJECTION
2431 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2432 	if (un->sd_injection_mask & component) {
2433 		mutex_enter(&sd_log_mutex);
2434 		va_start(ap, fmt);
2435 		(void) vsprintf(sd_log_buf, fmt, ap);
2436 		va_end(ap);
2437 		sd_injection_log(sd_log_buf, un);
2438 		mutex_exit(&sd_log_mutex);
2439 	}
2440 #endif
2441 }
2442 
2443 
2444 /*
2445  *    Function: sdprobe
2446  *
2447  * Description: This is the driver probe(9e) entry point function.
2448  *
2449  *   Arguments: devi - opaque device info handle
2450  *
2451  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2452  *              DDI_PROBE_FAILURE: If the probe failed.
2453  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2454  *				   but may be present in the future.
2455  */
2456 
2457 static int
2458 sdprobe(dev_info_t *devi)
2459 {
2460 	struct scsi_device	*devp;
2461 	int			rval;
2462 	int			instance;
2463 
2464 	/*
2465 	 * if it wasn't for pln, sdprobe could actually be nulldev
2466 	 * in the "__fibre" case.
2467 	 */
2468 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2469 		return (DDI_PROBE_DONTCARE);
2470 	}
2471 
2472 	devp = ddi_get_driver_private(devi);
2473 
2474 	if (devp == NULL) {
2475 		/* Ooops... nexus driver is mis-configured... */
2476 		return (DDI_PROBE_FAILURE);
2477 	}
2478 
2479 	instance = ddi_get_instance(devi);
2480 
2481 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2482 		return (DDI_PROBE_PARTIAL);
2483 	}
2484 
2485 	/*
2486 	 * Call the SCSA utility probe routine to see if we actually
2487 	 * have a target at this SCSI nexus.
2488 	 */
2489 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2490 	case SCSIPROBE_EXISTS:
2491 		switch (devp->sd_inq->inq_dtype) {
2492 		case DTYPE_DIRECT:
2493 			rval = DDI_PROBE_SUCCESS;
2494 			break;
2495 		case DTYPE_RODIRECT:
2496 			/* CDs etc. Can be removable media */
2497 			rval = DDI_PROBE_SUCCESS;
2498 			break;
2499 		case DTYPE_OPTICAL:
2500 			/*
2501 			 * Rewritable optical driver HP115AA
2502 			 * Can also be removable media
2503 			 */
2504 
2505 			/*
2506 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2507 			 * pre solaris 9 sparc sd behavior is required
2508 			 *
2509 			 * If first time through and sd_dtype_optical_bind
2510 			 * has not been set in /etc/system check properties
2511 			 */
2512 
2513 			if (sd_dtype_optical_bind  < 0) {
2514 			    sd_dtype_optical_bind = ddi_prop_get_int
2515 				(DDI_DEV_T_ANY,	devi,	0,
2516 				"optical-device-bind",	1);
2517 			}
2518 
2519 			if (sd_dtype_optical_bind == 0) {
2520 				rval = DDI_PROBE_FAILURE;
2521 			} else {
2522 				rval = DDI_PROBE_SUCCESS;
2523 			}
2524 			break;
2525 
2526 		case DTYPE_NOTPRESENT:
2527 		default:
2528 			rval = DDI_PROBE_FAILURE;
2529 			break;
2530 		}
2531 		break;
2532 	default:
2533 		rval = DDI_PROBE_PARTIAL;
2534 		break;
2535 	}
2536 
2537 	/*
2538 	 * This routine checks for resource allocation prior to freeing,
2539 	 * so it will take care of the "smart probing" case where a
2540 	 * scsi_probe() may or may not have been issued and will *not*
2541 	 * free previously-freed resources.
2542 	 */
2543 	scsi_unprobe(devp);
2544 	return (rval);
2545 }
2546 
2547 
2548 /*
2549  *    Function: sdinfo
2550  *
2551  * Description: This is the driver getinfo(9e) entry point function.
2552  * 		Given the device number, return the devinfo pointer from
2553  *		the scsi_device structure or the instance number
2554  *		associated with the dev_t.
2555  *
2556  *   Arguments: dip     - pointer to device info structure
2557  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2558  *			  DDI_INFO_DEVT2INSTANCE)
2559  *		arg     - driver dev_t
2560  *		resultp - user buffer for request response
2561  *
2562  * Return Code: DDI_SUCCESS
2563  *              DDI_FAILURE
2564  */
2565 /* ARGSUSED */
2566 static int
2567 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2568 {
2569 	struct sd_lun	*un;
2570 	dev_t		dev;
2571 	int		instance;
2572 	int		error;
2573 
2574 	switch (infocmd) {
2575 	case DDI_INFO_DEVT2DEVINFO:
2576 		dev = (dev_t)arg;
2577 		instance = SDUNIT(dev);
2578 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2579 			return (DDI_FAILURE);
2580 		}
2581 		*result = (void *) SD_DEVINFO(un);
2582 		error = DDI_SUCCESS;
2583 		break;
2584 	case DDI_INFO_DEVT2INSTANCE:
2585 		dev = (dev_t)arg;
2586 		instance = SDUNIT(dev);
2587 		*result = (void *)(uintptr_t)instance;
2588 		error = DDI_SUCCESS;
2589 		break;
2590 	default:
2591 		error = DDI_FAILURE;
2592 	}
2593 	return (error);
2594 }
2595 
2596 /*
2597  *    Function: sd_prop_op
2598  *
2599  * Description: This is the driver prop_op(9e) entry point function.
2600  *		Return the number of blocks for the partition in question
2601  *		or forward the request to the property facilities.
2602  *
2603  *   Arguments: dev       - device number
2604  *		dip       - pointer to device info structure
2605  *		prop_op   - property operator
2606  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2607  *		name      - pointer to property name
2608  *		valuep    - pointer or address of the user buffer
2609  *		lengthp   - property length
2610  *
2611  * Return Code: DDI_PROP_SUCCESS
2612  *              DDI_PROP_NOT_FOUND
2613  *              DDI_PROP_UNDEFINED
2614  *              DDI_PROP_NO_MEMORY
2615  *              DDI_PROP_BUF_TOO_SMALL
2616  */
2617 
2618 static int
2619 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2620 	char *name, caddr_t valuep, int *lengthp)
2621 {
2622 	int		instance = ddi_get_instance(dip);
2623 	struct sd_lun	*un;
2624 	uint64_t	nblocks64;
2625 
2626 	/*
2627 	 * Our dynamic properties are all device specific and size oriented.
2628 	 * Requests issued under conditions where size is valid are passed
2629 	 * to ddi_prop_op_nblocks with the size information, otherwise the
2630 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
2631 	 */
2632 	un = ddi_get_soft_state(sd_state, instance);
2633 	if ((dev == DDI_DEV_T_ANY) || (un == NULL) ||
2634 	    (un->un_f_geometry_is_valid == FALSE)) {
2635 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2636 		    name, valuep, lengthp));
2637 	} else {
2638 		/* get nblocks value */
2639 		ASSERT(!mutex_owned(SD_MUTEX(un)));
2640 		mutex_enter(SD_MUTEX(un));
2641 		nblocks64 = (ulong_t)un->un_map[SDPART(dev)].dkl_nblk;
2642 		mutex_exit(SD_MUTEX(un));
2643 
2644 		return (ddi_prop_op_nblocks(dev, dip, prop_op, mod_flags,
2645 		    name, valuep, lengthp, nblocks64));
2646 	}
2647 }
2648 
2649 /*
2650  * The following functions are for smart probing:
2651  * sd_scsi_probe_cache_init()
2652  * sd_scsi_probe_cache_fini()
2653  * sd_scsi_clear_probe_cache()
2654  * sd_scsi_probe_with_cache()
2655  */
2656 
2657 /*
2658  *    Function: sd_scsi_probe_cache_init
2659  *
2660  * Description: Initializes the probe response cache mutex and head pointer.
2661  *
2662  *     Context: Kernel thread context
2663  */
2664 
2665 static void
2666 sd_scsi_probe_cache_init(void)
2667 {
2668 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2669 	sd_scsi_probe_cache_head = NULL;
2670 }
2671 
2672 
2673 /*
2674  *    Function: sd_scsi_probe_cache_fini
2675  *
2676  * Description: Frees all resources associated with the probe response cache.
2677  *
2678  *     Context: Kernel thread context
2679  */
2680 
2681 static void
2682 sd_scsi_probe_cache_fini(void)
2683 {
2684 	struct sd_scsi_probe_cache *cp;
2685 	struct sd_scsi_probe_cache *ncp;
2686 
2687 	/* Clean up our smart probing linked list */
2688 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2689 		ncp = cp->next;
2690 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2691 	}
2692 	sd_scsi_probe_cache_head = NULL;
2693 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2694 }
2695 
2696 
2697 /*
2698  *    Function: sd_scsi_clear_probe_cache
2699  *
2700  * Description: This routine clears the probe response cache. This is
2701  *		done when open() returns ENXIO so that when deferred
2702  *		attach is attempted (possibly after a device has been
2703  *		turned on) we will retry the probe. Since we don't know
2704  *		which target we failed to open, we just clear the
2705  *		entire cache.
2706  *
2707  *     Context: Kernel thread context
2708  */
2709 
2710 static void
2711 sd_scsi_clear_probe_cache(void)
2712 {
2713 	struct sd_scsi_probe_cache	*cp;
2714 	int				i;
2715 
2716 	mutex_enter(&sd_scsi_probe_cache_mutex);
2717 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2718 		/*
2719 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2720 		 * force probing to be performed the next time
2721 		 * sd_scsi_probe_with_cache is called.
2722 		 */
2723 		for (i = 0; i < NTARGETS_WIDE; i++) {
2724 			cp->cache[i] = SCSIPROBE_EXISTS;
2725 		}
2726 	}
2727 	mutex_exit(&sd_scsi_probe_cache_mutex);
2728 }
2729 
2730 
2731 /*
2732  *    Function: sd_scsi_probe_with_cache
2733  *
2734  * Description: This routine implements support for a scsi device probe
2735  *		with cache. The driver maintains a cache of the target
2736  *		responses to scsi probes. If we get no response from a
2737  *		target during a probe inquiry, we remember that, and we
2738  *		avoid additional calls to scsi_probe on non-zero LUNs
2739  *		on the same target until the cache is cleared. By doing
2740  *		so we avoid the 1/4 sec selection timeout for nonzero
2741  *		LUNs. lun0 of a target is always probed.
2742  *
2743  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2744  *              waitfunc - indicates what the allocator routines should
2745  *			   do when resources are not available. This value
2746  *			   is passed on to scsi_probe() when that routine
2747  *			   is called.
2748  *
2749  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2750  *		otherwise the value returned by scsi_probe(9F).
2751  *
2752  *     Context: Kernel thread context
2753  */
2754 
2755 static int
2756 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2757 {
2758 	struct sd_scsi_probe_cache	*cp;
2759 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2760 	int		lun, tgt;
2761 
2762 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2763 	    SCSI_ADDR_PROP_LUN, 0);
2764 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2765 	    SCSI_ADDR_PROP_TARGET, -1);
2766 
2767 	/* Make sure caching enabled and target in range */
2768 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2769 		/* do it the old way (no cache) */
2770 		return (scsi_probe(devp, waitfn));
2771 	}
2772 
2773 	mutex_enter(&sd_scsi_probe_cache_mutex);
2774 
2775 	/* Find the cache for this scsi bus instance */
2776 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2777 		if (cp->pdip == pdip) {
2778 			break;
2779 		}
2780 	}
2781 
2782 	/* If we can't find a cache for this pdip, create one */
2783 	if (cp == NULL) {
2784 		int i;
2785 
2786 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2787 		    KM_SLEEP);
2788 		cp->pdip = pdip;
2789 		cp->next = sd_scsi_probe_cache_head;
2790 		sd_scsi_probe_cache_head = cp;
2791 		for (i = 0; i < NTARGETS_WIDE; i++) {
2792 			cp->cache[i] = SCSIPROBE_EXISTS;
2793 		}
2794 	}
2795 
2796 	mutex_exit(&sd_scsi_probe_cache_mutex);
2797 
2798 	/* Recompute the cache for this target if LUN zero */
2799 	if (lun == 0) {
2800 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2801 	}
2802 
2803 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2804 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2805 		return (SCSIPROBE_NORESP);
2806 	}
2807 
2808 	/* Do the actual probe; save & return the result */
2809 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2810 }
2811 
2812 
2813 /*
2814  *    Function: sd_spin_up_unit
2815  *
2816  * Description: Issues the following commands to spin-up the device:
2817  *		START STOP UNIT, and INQUIRY.
2818  *
2819  *   Arguments: un - driver soft state (unit) structure
2820  *
2821  * Return Code: 0 - success
2822  *		EIO - failure
2823  *		EACCES - reservation conflict
2824  *
2825  *     Context: Kernel thread context
2826  */
2827 
2828 static int
2829 sd_spin_up_unit(struct sd_lun *un)
2830 {
2831 	size_t	resid		= 0;
2832 	int	has_conflict	= FALSE;
2833 	uchar_t *bufaddr;
2834 
2835 	ASSERT(un != NULL);
2836 
2837 	/*
2838 	 * Send a throwaway START UNIT command.
2839 	 *
2840 	 * If we fail on this, we don't care presently what precisely
2841 	 * is wrong.  EMC's arrays will also fail this with a check
2842 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
2843 	 * we don't want to fail the attach because it may become
2844 	 * "active" later.
2845 	 */
2846 	if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START, SD_PATH_DIRECT)
2847 	    == EACCES)
2848 		has_conflict = TRUE;
2849 
2850 	/*
2851 	 * Send another INQUIRY command to the target. This is necessary for
2852 	 * non-removable media direct access devices because their INQUIRY data
2853 	 * may not be fully qualified until they are spun up (perhaps via the
2854 	 * START command above).  Note: This seems to be needed for some
2855 	 * legacy devices only.) The INQUIRY command should succeed even if a
2856 	 * Reservation Conflict is present.
2857 	 */
2858 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
2859 	if (sd_send_scsi_INQUIRY(un, bufaddr, SUN_INQSIZE, 0, 0, &resid) != 0) {
2860 		kmem_free(bufaddr, SUN_INQSIZE);
2861 		return (EIO);
2862 	}
2863 
2864 	/*
2865 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
2866 	 * Note that this routine does not return a failure here even if the
2867 	 * INQUIRY command did not return any data.  This is a legacy behavior.
2868 	 */
2869 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
2870 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
2871 	}
2872 
2873 	kmem_free(bufaddr, SUN_INQSIZE);
2874 
2875 	/* If we hit a reservation conflict above, tell the caller. */
2876 	if (has_conflict == TRUE) {
2877 		return (EACCES);
2878 	}
2879 
2880 	return (0);
2881 }
2882 
2883 #ifdef _LP64
2884 /*
2885  *    Function: sd_enable_descr_sense
2886  *
2887  * Description: This routine attempts to select descriptor sense format
2888  *		using the Control mode page.  Devices that support 64 bit
2889  *		LBAs (for >2TB luns) should also implement descriptor
2890  *		sense data so we will call this function whenever we see
2891  *		a lun larger than 2TB.  If for some reason the device
2892  *		supports 64 bit LBAs but doesn't support descriptor sense
2893  *		presumably the mode select will fail.  Everything will
2894  *		continue to work normally except that we will not get
2895  *		complete sense data for commands that fail with an LBA
2896  *		larger than 32 bits.
2897  *
2898  *   Arguments: un - driver soft state (unit) structure
2899  *
2900  *     Context: Kernel thread context only
2901  */
2902 
2903 static void
2904 sd_enable_descr_sense(struct sd_lun *un)
2905 {
2906 	uchar_t			*header;
2907 	struct mode_control_scsi3 *ctrl_bufp;
2908 	size_t			buflen;
2909 	size_t			bd_len;
2910 
2911 	/*
2912 	 * Read MODE SENSE page 0xA, Control Mode Page
2913 	 */
2914 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
2915 	    sizeof (struct mode_control_scsi3);
2916 	header = kmem_zalloc(buflen, KM_SLEEP);
2917 	if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
2918 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT) != 0) {
2919 		SD_ERROR(SD_LOG_COMMON, un,
2920 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
2921 		goto eds_exit;
2922 	}
2923 
2924 	/*
2925 	 * Determine size of Block Descriptors in order to locate
2926 	 * the mode page data. ATAPI devices return 0, SCSI devices
2927 	 * should return MODE_BLK_DESC_LENGTH.
2928 	 */
2929 	bd_len  = ((struct mode_header *)header)->bdesc_length;
2930 
2931 	ctrl_bufp = (struct mode_control_scsi3 *)
2932 	    (header + MODE_HEADER_LENGTH + bd_len);
2933 
2934 	/*
2935 	 * Clear PS bit for MODE SELECT
2936 	 */
2937 	ctrl_bufp->mode_page.ps = 0;
2938 
2939 	/*
2940 	 * Set D_SENSE to enable descriptor sense format.
2941 	 */
2942 	ctrl_bufp->d_sense = 1;
2943 
2944 	/*
2945 	 * Use MODE SELECT to commit the change to the D_SENSE bit
2946 	 */
2947 	if (sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
2948 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT) != 0) {
2949 		SD_INFO(SD_LOG_COMMON, un,
2950 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
2951 		goto eds_exit;
2952 	}
2953 
2954 eds_exit:
2955 	kmem_free(header, buflen);
2956 }
2957 #endif /* _LP64 */
2958 
2959 
2960 /*
2961  *    Function: sd_set_mmc_caps
2962  *
2963  * Description: This routine determines if the device is MMC compliant and if
2964  *		the device supports CDDA via a mode sense of the CDVD
2965  *		capabilities mode page. Also checks if the device is a
2966  *		dvdram writable device.
2967  *
2968  *   Arguments: un - driver soft state (unit) structure
2969  *
2970  *     Context: Kernel thread context only
2971  */
2972 
2973 static void
2974 sd_set_mmc_caps(struct sd_lun *un)
2975 {
2976 	struct mode_header_grp2		*sense_mhp;
2977 	uchar_t				*sense_page;
2978 	caddr_t				buf;
2979 	int				bd_len;
2980 	int				status;
2981 	struct uscsi_cmd		com;
2982 	int				rtn;
2983 	uchar_t				*out_data_rw, *out_data_hd;
2984 	uchar_t				*rqbuf_rw, *rqbuf_hd;
2985 
2986 	ASSERT(un != NULL);
2987 
2988 	/*
2989 	 * The flags which will be set in this function are - mmc compliant,
2990 	 * dvdram writable device, cdda support. Initialize them to FALSE
2991 	 * and if a capability is detected - it will be set to TRUE.
2992 	 */
2993 	un->un_f_mmc_cap = FALSE;
2994 	un->un_f_dvdram_writable_device = FALSE;
2995 	un->un_f_cfg_cdda = FALSE;
2996 
2997 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
2998 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
2999 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3000 
3001 	if (status != 0) {
3002 		/* command failed; just return */
3003 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3004 		return;
3005 	}
3006 	/*
3007 	 * If the mode sense request for the CDROM CAPABILITIES
3008 	 * page (0x2A) succeeds the device is assumed to be MMC.
3009 	 */
3010 	un->un_f_mmc_cap = TRUE;
3011 
3012 	/* Get to the page data */
3013 	sense_mhp = (struct mode_header_grp2 *)buf;
3014 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3015 	    sense_mhp->bdesc_length_lo;
3016 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3017 		/*
3018 		 * We did not get back the expected block descriptor
3019 		 * length so we cannot determine if the device supports
3020 		 * CDDA. However, we still indicate the device is MMC
3021 		 * according to the successful response to the page
3022 		 * 0x2A mode sense request.
3023 		 */
3024 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3025 		    "sd_set_mmc_caps: Mode Sense returned "
3026 		    "invalid block descriptor length\n");
3027 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3028 		return;
3029 	}
3030 
3031 	/* See if read CDDA is supported */
3032 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3033 	    bd_len);
3034 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3035 
3036 	/* See if writing DVD RAM is supported. */
3037 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3038 	if (un->un_f_dvdram_writable_device == TRUE) {
3039 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3040 		return;
3041 	}
3042 
3043 	/*
3044 	 * If the device presents DVD or CD capabilities in the mode
3045 	 * page, we can return here since a RRD will not have
3046 	 * these capabilities.
3047 	 */
3048 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3049 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3050 		return;
3051 	}
3052 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3053 
3054 	/*
3055 	 * If un->un_f_dvdram_writable_device is still FALSE,
3056 	 * check for a Removable Rigid Disk (RRD).  A RRD
3057 	 * device is identified by the features RANDOM_WRITABLE and
3058 	 * HARDWARE_DEFECT_MANAGEMENT.
3059 	 */
3060 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3061 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3062 
3063 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3064 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3065 	    RANDOM_WRITABLE);
3066 	if (rtn != 0) {
3067 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3068 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3069 		return;
3070 	}
3071 
3072 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3073 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3074 
3075 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3076 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3077 	    HARDWARE_DEFECT_MANAGEMENT);
3078 	if (rtn == 0) {
3079 		/*
3080 		 * We have good information, check for random writable
3081 		 * and hardware defect features.
3082 		 */
3083 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3084 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3085 			un->un_f_dvdram_writable_device = TRUE;
3086 		}
3087 	}
3088 
3089 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3090 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3091 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3092 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3093 }
3094 
3095 /*
3096  *    Function: sd_check_for_writable_cd
3097  *
3098  * Description: This routine determines if the media in the device is
3099  *		writable or not. It uses the get configuration command (0x46)
3100  *		to determine if the media is writable
3101  *
3102  *   Arguments: un - driver soft state (unit) structure
3103  *
3104  *     Context: Never called at interrupt context.
3105  */
3106 
3107 static void
3108 sd_check_for_writable_cd(struct sd_lun *un)
3109 {
3110 	struct uscsi_cmd		com;
3111 	uchar_t				*out_data;
3112 	uchar_t				*rqbuf;
3113 	int				rtn;
3114 	uchar_t				*out_data_rw, *out_data_hd;
3115 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3116 	struct mode_header_grp2		*sense_mhp;
3117 	uchar_t				*sense_page;
3118 	caddr_t				buf;
3119 	int				bd_len;
3120 	int				status;
3121 
3122 	ASSERT(un != NULL);
3123 	ASSERT(mutex_owned(SD_MUTEX(un)));
3124 
3125 	/*
3126 	 * Initialize the writable media to false, if configuration info.
3127 	 * tells us otherwise then only we will set it.
3128 	 */
3129 	un->un_f_mmc_writable_media = FALSE;
3130 	mutex_exit(SD_MUTEX(un));
3131 
3132 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3133 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3134 
3135 	rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf, SENSE_LENGTH,
3136 	    out_data, SD_PROFILE_HEADER_LEN);
3137 
3138 	mutex_enter(SD_MUTEX(un));
3139 	if (rtn == 0) {
3140 		/*
3141 		 * We have good information, check for writable DVD.
3142 		 */
3143 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3144 			un->un_f_mmc_writable_media = TRUE;
3145 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3146 			kmem_free(rqbuf, SENSE_LENGTH);
3147 			return;
3148 		}
3149 	}
3150 
3151 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3152 	kmem_free(rqbuf, SENSE_LENGTH);
3153 
3154 	/*
3155 	 * Determine if this is a RRD type device.
3156 	 */
3157 	mutex_exit(SD_MUTEX(un));
3158 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3159 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3160 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3161 	mutex_enter(SD_MUTEX(un));
3162 	if (status != 0) {
3163 		/* command failed; just return */
3164 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3165 		return;
3166 	}
3167 
3168 	/* Get to the page data */
3169 	sense_mhp = (struct mode_header_grp2 *)buf;
3170 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3171 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3172 		/*
3173 		 * We did not get back the expected block descriptor length so
3174 		 * we cannot check the mode page.
3175 		 */
3176 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3177 		    "sd_check_for_writable_cd: Mode Sense returned "
3178 		    "invalid block descriptor length\n");
3179 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3180 		return;
3181 	}
3182 
3183 	/*
3184 	 * If the device presents DVD or CD capabilities in the mode
3185 	 * page, we can return here since a RRD device will not have
3186 	 * these capabilities.
3187 	 */
3188 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3189 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3190 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3191 		return;
3192 	}
3193 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3194 
3195 	/*
3196 	 * If un->un_f_mmc_writable_media is still FALSE,
3197 	 * check for RRD type media.  A RRD device is identified
3198 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3199 	 */
3200 	mutex_exit(SD_MUTEX(un));
3201 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3202 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3203 
3204 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3205 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3206 	    RANDOM_WRITABLE);
3207 	if (rtn != 0) {
3208 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3209 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3210 		mutex_enter(SD_MUTEX(un));
3211 		return;
3212 	}
3213 
3214 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3215 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3216 
3217 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3218 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3219 	    HARDWARE_DEFECT_MANAGEMENT);
3220 	mutex_enter(SD_MUTEX(un));
3221 	if (rtn == 0) {
3222 		/*
3223 		 * We have good information, check for random writable
3224 		 * and hardware defect features as current.
3225 		 */
3226 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3227 		    (out_data_rw[10] & 0x1) &&
3228 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3229 		    (out_data_hd[10] & 0x1)) {
3230 			un->un_f_mmc_writable_media = TRUE;
3231 		}
3232 	}
3233 
3234 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3235 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3236 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3237 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3238 }
3239 
3240 /*
3241  *    Function: sd_read_unit_properties
3242  *
3243  * Description: The following implements a property lookup mechanism.
3244  *		Properties for particular disks (keyed on vendor, model
3245  *		and rev numbers) are sought in the sd.conf file via
3246  *		sd_process_sdconf_file(), and if not found there, are
3247  *		looked for in a list hardcoded in this driver via
3248  *		sd_process_sdconf_table() Once located the properties
3249  *		are used to update the driver unit structure.
3250  *
3251  *   Arguments: un - driver soft state (unit) structure
3252  */
3253 
3254 static void
3255 sd_read_unit_properties(struct sd_lun *un)
3256 {
3257 	/*
3258 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3259 	 * the "sd-config-list" property (from the sd.conf file) or if
3260 	 * there was not a match for the inquiry vid/pid. If this event
3261 	 * occurs the static driver configuration table is searched for
3262 	 * a match.
3263 	 */
3264 	ASSERT(un != NULL);
3265 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3266 		sd_process_sdconf_table(un);
3267 	}
3268 
3269 	/* check for LSI device */
3270 	sd_is_lsi(un);
3271 
3272 
3273 }
3274 
3275 
3276 /*
3277  *    Function: sd_process_sdconf_file
3278  *
3279  * Description: Use ddi_getlongprop to obtain the properties from the
3280  *		driver's config file (ie, sd.conf) and update the driver
3281  *		soft state structure accordingly.
3282  *
3283  *   Arguments: un - driver soft state (unit) structure
3284  *
3285  * Return Code: SD_SUCCESS - The properties were successfully set according
3286  *			     to the driver configuration file.
3287  *		SD_FAILURE - The driver config list was not obtained or
3288  *			     there was no vid/pid match. This indicates that
3289  *			     the static config table should be used.
3290  *
3291  * The config file has a property, "sd-config-list", which consists of
3292  * one or more duplets as follows:
3293  *
3294  *  sd-config-list=
3295  *	<duplet>,
3296  *	[<duplet>,]
3297  *	[<duplet>];
3298  *
3299  * The structure of each duplet is as follows:
3300  *
3301  *  <duplet>:= <vid+pid>,<data-property-name_list>
3302  *
3303  * The first entry of the duplet is the device ID string (the concatenated
3304  * vid & pid; not to be confused with a device_id).  This is defined in
3305  * the same way as in the sd_disk_table.
3306  *
3307  * The second part of the duplet is a string that identifies a
3308  * data-property-name-list. The data-property-name-list is defined as
3309  * follows:
3310  *
3311  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3312  *
3313  * The syntax of <data-property-name> depends on the <version> field.
3314  *
3315  * If version = SD_CONF_VERSION_1 we have the following syntax:
3316  *
3317  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3318  *
3319  * where the prop0 value will be used to set prop0 if bit0 set in the
3320  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3321  *
3322  */
3323 
3324 static int
3325 sd_process_sdconf_file(struct sd_lun *un)
3326 {
3327 	char	*config_list = NULL;
3328 	int	config_list_len;
3329 	int	len;
3330 	int	dupletlen = 0;
3331 	char	*vidptr;
3332 	int	vidlen;
3333 	char	*dnlist_ptr;
3334 	char	*dataname_ptr;
3335 	int	dnlist_len;
3336 	int	dataname_len;
3337 	int	*data_list;
3338 	int	data_list_len;
3339 	int	rval = SD_FAILURE;
3340 	int	i;
3341 
3342 	ASSERT(un != NULL);
3343 
3344 	/* Obtain the configuration list associated with the .conf file */
3345 	if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), DDI_PROP_DONTPASS,
3346 	    sd_config_list, (caddr_t)&config_list, &config_list_len)
3347 	    != DDI_PROP_SUCCESS) {
3348 		return (SD_FAILURE);
3349 	}
3350 
3351 	/*
3352 	 * Compare vids in each duplet to the inquiry vid - if a match is
3353 	 * made, get the data value and update the soft state structure
3354 	 * accordingly.
3355 	 *
3356 	 * Note: This algorithm is complex and difficult to maintain. It should
3357 	 * be replaced with a more robust implementation.
3358 	 */
3359 	for (len = config_list_len, vidptr = config_list; len > 0;
3360 	    vidptr += dupletlen, len -= dupletlen) {
3361 		/*
3362 		 * Note: The assumption here is that each vid entry is on
3363 		 * a unique line from its associated duplet.
3364 		 */
3365 		vidlen = dupletlen = (int)strlen(vidptr);
3366 		if ((vidlen == 0) ||
3367 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3368 			dupletlen++;
3369 			continue;
3370 		}
3371 
3372 		/*
3373 		 * dnlist contains 1 or more blank separated
3374 		 * data-property-name entries
3375 		 */
3376 		dnlist_ptr = vidptr + vidlen + 1;
3377 		dnlist_len = (int)strlen(dnlist_ptr);
3378 		dupletlen += dnlist_len + 2;
3379 
3380 		/*
3381 		 * Set a pointer for the first data-property-name
3382 		 * entry in the list
3383 		 */
3384 		dataname_ptr = dnlist_ptr;
3385 		dataname_len = 0;
3386 
3387 		/*
3388 		 * Loop through all data-property-name entries in the
3389 		 * data-property-name-list setting the properties for each.
3390 		 */
3391 		while (dataname_len < dnlist_len) {
3392 			int version;
3393 
3394 			/*
3395 			 * Determine the length of the current
3396 			 * data-property-name entry by indexing until a
3397 			 * blank or NULL is encountered. When the space is
3398 			 * encountered reset it to a NULL for compliance
3399 			 * with ddi_getlongprop().
3400 			 */
3401 			for (i = 0; ((dataname_ptr[i] != ' ') &&
3402 			    (dataname_ptr[i] != '\0')); i++) {
3403 				;
3404 			}
3405 
3406 			dataname_len += i;
3407 			/* If not null terminated, Make it so */
3408 			if (dataname_ptr[i] == ' ') {
3409 				dataname_ptr[i] = '\0';
3410 			}
3411 			dataname_len++;
3412 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3413 			    "sd_process_sdconf_file: disk:%s, data:%s\n",
3414 			    vidptr, dataname_ptr);
3415 
3416 			/* Get the data list */
3417 			if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), 0,
3418 			    dataname_ptr, (caddr_t)&data_list, &data_list_len)
3419 			    != DDI_PROP_SUCCESS) {
3420 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3421 				    "sd_process_sdconf_file: data property (%s)"
3422 				    " has no value\n", dataname_ptr);
3423 				dataname_ptr = dnlist_ptr + dataname_len;
3424 				continue;
3425 			}
3426 
3427 			version = data_list[0];
3428 
3429 			if (version == SD_CONF_VERSION_1) {
3430 				sd_tunables values;
3431 
3432 				/* Set the properties */
3433 				if (sd_chk_vers1_data(un, data_list[1],
3434 				    &data_list[2], data_list_len, dataname_ptr)
3435 				    == SD_SUCCESS) {
3436 					sd_get_tunables_from_conf(un,
3437 					    data_list[1], &data_list[2],
3438 					    &values);
3439 					sd_set_vers1_properties(un,
3440 					    data_list[1], &values);
3441 					rval = SD_SUCCESS;
3442 				} else {
3443 					rval = SD_FAILURE;
3444 				}
3445 			} else {
3446 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3447 				    "data property %s version 0x%x is invalid.",
3448 				    dataname_ptr, version);
3449 				rval = SD_FAILURE;
3450 			}
3451 			kmem_free(data_list, data_list_len);
3452 			dataname_ptr = dnlist_ptr + dataname_len;
3453 		}
3454 	}
3455 
3456 	/* free up the memory allocated by ddi_getlongprop */
3457 	if (config_list) {
3458 		kmem_free(config_list, config_list_len);
3459 	}
3460 
3461 	return (rval);
3462 }
3463 
3464 /*
3465  *    Function: sd_get_tunables_from_conf()
3466  *
3467  *
3468  *    This function reads the data list from the sd.conf file and pulls
3469  *    the values that can have numeric values as arguments and places
3470  *    the values in the apropriate sd_tunables member.
3471  *    Since the order of the data list members varies across platforms
3472  *    This function reads them from the data list in a platform specific
3473  *    order and places them into the correct sd_tunable member that is
3474  *    a consistant across all platforms.
3475  */
3476 static void
3477 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3478     sd_tunables *values)
3479 {
3480 	int i;
3481 	int mask;
3482 
3483 	bzero(values, sizeof (sd_tunables));
3484 
3485 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3486 
3487 		mask = 1 << i;
3488 		if (mask > flags) {
3489 			break;
3490 		}
3491 
3492 		switch (mask & flags) {
3493 		case 0:	/* This mask bit not set in flags */
3494 			continue;
3495 		case SD_CONF_BSET_THROTTLE:
3496 			values->sdt_throttle = data_list[i];
3497 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3498 			    "sd_get_tunables_from_conf: throttle = %d\n",
3499 			    values->sdt_throttle);
3500 			break;
3501 		case SD_CONF_BSET_CTYPE:
3502 			values->sdt_ctype = data_list[i];
3503 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3504 			    "sd_get_tunables_from_conf: ctype = %d\n",
3505 			    values->sdt_ctype);
3506 			break;
3507 		case SD_CONF_BSET_NRR_COUNT:
3508 			values->sdt_not_rdy_retries = data_list[i];
3509 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3510 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
3511 			    values->sdt_not_rdy_retries);
3512 			break;
3513 		case SD_CONF_BSET_BSY_RETRY_COUNT:
3514 			values->sdt_busy_retries = data_list[i];
3515 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3516 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
3517 			    values->sdt_busy_retries);
3518 			break;
3519 		case SD_CONF_BSET_RST_RETRIES:
3520 			values->sdt_reset_retries = data_list[i];
3521 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3522 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
3523 			    values->sdt_reset_retries);
3524 			break;
3525 		case SD_CONF_BSET_RSV_REL_TIME:
3526 			values->sdt_reserv_rel_time = data_list[i];
3527 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3528 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
3529 			    values->sdt_reserv_rel_time);
3530 			break;
3531 		case SD_CONF_BSET_MIN_THROTTLE:
3532 			values->sdt_min_throttle = data_list[i];
3533 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3534 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
3535 			    values->sdt_min_throttle);
3536 			break;
3537 		case SD_CONF_BSET_DISKSORT_DISABLED:
3538 			values->sdt_disk_sort_dis = data_list[i];
3539 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3540 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
3541 			    values->sdt_disk_sort_dis);
3542 			break;
3543 		case SD_CONF_BSET_LUN_RESET_ENABLED:
3544 			values->sdt_lun_reset_enable = data_list[i];
3545 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3546 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
3547 			    "\n", values->sdt_lun_reset_enable);
3548 			break;
3549 		}
3550 	}
3551 }
3552 
3553 /*
3554  *    Function: sd_process_sdconf_table
3555  *
3556  * Description: Search the static configuration table for a match on the
3557  *		inquiry vid/pid and update the driver soft state structure
3558  *		according to the table property values for the device.
3559  *
3560  *		The form of a configuration table entry is:
3561  *		  <vid+pid>,<flags>,<property-data>
3562  *		  "SEAGATE ST42400N",1,63,0,0			(Fibre)
3563  *		  "SEAGATE ST42400N",1,63,0,0,0,0		(Sparc)
3564  *		  "SEAGATE ST42400N",1,63,0,0,0,0,0,0,0,0,0,0	(Intel)
3565  *
3566  *   Arguments: un - driver soft state (unit) structure
3567  */
3568 
3569 static void
3570 sd_process_sdconf_table(struct sd_lun *un)
3571 {
3572 	char	*id = NULL;
3573 	int	table_index;
3574 	int	idlen;
3575 
3576 	ASSERT(un != NULL);
3577 	for (table_index = 0; table_index < sd_disk_table_size;
3578 	    table_index++) {
3579 		id = sd_disk_table[table_index].device_id;
3580 		idlen = strlen(id);
3581 		if (idlen == 0) {
3582 			continue;
3583 		}
3584 
3585 		/*
3586 		 * The static configuration table currently does not
3587 		 * implement version 10 properties. Additionally,
3588 		 * multiple data-property-name entries are not
3589 		 * implemented in the static configuration table.
3590 		 */
3591 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
3592 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3593 			    "sd_process_sdconf_table: disk %s\n", id);
3594 			sd_set_vers1_properties(un,
3595 			    sd_disk_table[table_index].flags,
3596 			    sd_disk_table[table_index].properties);
3597 			break;
3598 		}
3599 	}
3600 }
3601 
3602 
3603 /*
3604  *    Function: sd_sdconf_id_match
3605  *
3606  * Description: This local function implements a case sensitive vid/pid
3607  *		comparison as well as the boundary cases of wild card and
3608  *		multiple blanks.
3609  *
3610  *		Note: An implicit assumption made here is that the scsi
3611  *		inquiry structure will always keep the vid, pid and
3612  *		revision strings in consecutive sequence, so they can be
3613  *		read as a single string. If this assumption is not the
3614  *		case, a separate string, to be used for the check, needs
3615  *		to be built with these strings concatenated.
3616  *
3617  *   Arguments: un - driver soft state (unit) structure
3618  *		id - table or config file vid/pid
3619  *		idlen  - length of the vid/pid (bytes)
3620  *
3621  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3622  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3623  */
3624 
3625 static int
3626 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
3627 {
3628 	struct scsi_inquiry	*sd_inq;
3629 	int 			rval = SD_SUCCESS;
3630 
3631 	ASSERT(un != NULL);
3632 	sd_inq = un->un_sd->sd_inq;
3633 	ASSERT(id != NULL);
3634 
3635 	/*
3636 	 * We use the inq_vid as a pointer to a buffer containing the
3637 	 * vid and pid and use the entire vid/pid length of the table
3638 	 * entry for the comparison. This works because the inq_pid
3639 	 * data member follows inq_vid in the scsi_inquiry structure.
3640 	 */
3641 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
3642 		/*
3643 		 * The user id string is compared to the inquiry vid/pid
3644 		 * using a case insensitive comparison and ignoring
3645 		 * multiple spaces.
3646 		 */
3647 		rval = sd_blank_cmp(un, id, idlen);
3648 		if (rval != SD_SUCCESS) {
3649 			/*
3650 			 * User id strings that start and end with a "*"
3651 			 * are a special case. These do not have a
3652 			 * specific vendor, and the product string can
3653 			 * appear anywhere in the 16 byte PID portion of
3654 			 * the inquiry data. This is a simple strstr()
3655 			 * type search for the user id in the inquiry data.
3656 			 */
3657 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
3658 				char	*pidptr = &id[1];
3659 				int	i;
3660 				int	j;
3661 				int	pidstrlen = idlen - 2;
3662 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
3663 				    pidstrlen;
3664 
3665 				if (j < 0) {
3666 					return (SD_FAILURE);
3667 				}
3668 				for (i = 0; i < j; i++) {
3669 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
3670 					    pidptr, pidstrlen) == 0) {
3671 						rval = SD_SUCCESS;
3672 						break;
3673 					}
3674 				}
3675 			}
3676 		}
3677 	}
3678 	return (rval);
3679 }
3680 
3681 
3682 /*
3683  *    Function: sd_blank_cmp
3684  *
3685  * Description: If the id string starts and ends with a space, treat
3686  *		multiple consecutive spaces as equivalent to a single
3687  *		space. For example, this causes a sd_disk_table entry
3688  *		of " NEC CDROM " to match a device's id string of
3689  *		"NEC       CDROM".
3690  *
3691  *		Note: The success exit condition for this routine is if
3692  *		the pointer to the table entry is '\0' and the cnt of
3693  *		the inquiry length is zero. This will happen if the inquiry
3694  *		string returned by the device is padded with spaces to be
3695  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
3696  *		SCSI spec states that the inquiry string is to be padded with
3697  *		spaces.
3698  *
3699  *   Arguments: un - driver soft state (unit) structure
3700  *		id - table or config file vid/pid
3701  *		idlen  - length of the vid/pid (bytes)
3702  *
3703  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3704  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3705  */
3706 
3707 static int
3708 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
3709 {
3710 	char		*p1;
3711 	char		*p2;
3712 	int		cnt;
3713 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
3714 	    sizeof (SD_INQUIRY(un)->inq_pid);
3715 
3716 	ASSERT(un != NULL);
3717 	p2 = un->un_sd->sd_inq->inq_vid;
3718 	ASSERT(id != NULL);
3719 	p1 = id;
3720 
3721 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
3722 		/*
3723 		 * Note: string p1 is terminated by a NUL but string p2
3724 		 * isn't.  The end of p2 is determined by cnt.
3725 		 */
3726 		for (;;) {
3727 			/* skip over any extra blanks in both strings */
3728 			while ((*p1 != '\0') && (*p1 == ' ')) {
3729 				p1++;
3730 			}
3731 			while ((cnt != 0) && (*p2 == ' ')) {
3732 				p2++;
3733 				cnt--;
3734 			}
3735 
3736 			/* compare the two strings */
3737 			if ((cnt == 0) ||
3738 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
3739 				break;
3740 			}
3741 			while ((cnt > 0) &&
3742 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
3743 				p1++;
3744 				p2++;
3745 				cnt--;
3746 			}
3747 		}
3748 	}
3749 
3750 	/* return SD_SUCCESS if both strings match */
3751 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
3752 }
3753 
3754 
3755 /*
3756  *    Function: sd_chk_vers1_data
3757  *
3758  * Description: Verify the version 1 device properties provided by the
3759  *		user via the configuration file
3760  *
3761  *   Arguments: un	     - driver soft state (unit) structure
3762  *		flags	     - integer mask indicating properties to be set
3763  *		prop_list    - integer list of property values
3764  *		list_len     - length of user provided data
3765  *
3766  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
3767  *		SD_FAILURE - Indicates the user provided data is invalid
3768  */
3769 
3770 static int
3771 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
3772     int list_len, char *dataname_ptr)
3773 {
3774 	int i;
3775 	int mask = 1;
3776 	int index = 0;
3777 
3778 	ASSERT(un != NULL);
3779 
3780 	/* Check for a NULL property name and list */
3781 	if (dataname_ptr == NULL) {
3782 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3783 		    "sd_chk_vers1_data: NULL data property name.");
3784 		return (SD_FAILURE);
3785 	}
3786 	if (prop_list == NULL) {
3787 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3788 		    "sd_chk_vers1_data: %s NULL data property list.",
3789 		    dataname_ptr);
3790 		return (SD_FAILURE);
3791 	}
3792 
3793 	/* Display a warning if undefined bits are set in the flags */
3794 	if (flags & ~SD_CONF_BIT_MASK) {
3795 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3796 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
3797 		    "Properties not set.",
3798 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
3799 		return (SD_FAILURE);
3800 	}
3801 
3802 	/*
3803 	 * Verify the length of the list by identifying the highest bit set
3804 	 * in the flags and validating that the property list has a length
3805 	 * up to the index of this bit.
3806 	 */
3807 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3808 		if (flags & mask) {
3809 			index++;
3810 		}
3811 		mask = 1 << i;
3812 	}
3813 	if ((list_len / sizeof (int)) < (index + 2)) {
3814 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3815 		    "sd_chk_vers1_data: "
3816 		    "Data property list %s size is incorrect. "
3817 		    "Properties not set.", dataname_ptr);
3818 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
3819 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
3820 		return (SD_FAILURE);
3821 	}
3822 	return (SD_SUCCESS);
3823 }
3824 
3825 
3826 /*
3827  *    Function: sd_set_vers1_properties
3828  *
3829  * Description: Set version 1 device properties based on a property list
3830  *		retrieved from the driver configuration file or static
3831  *		configuration table. Version 1 properties have the format:
3832  *
3833  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3834  *
3835  *		where the prop0 value will be used to set prop0 if bit0
3836  *		is set in the flags
3837  *
3838  *   Arguments: un	     - driver soft state (unit) structure
3839  *		flags	     - integer mask indicating properties to be set
3840  *		prop_list    - integer list of property values
3841  */
3842 
3843 static void
3844 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
3845 {
3846 	ASSERT(un != NULL);
3847 
3848 	/*
3849 	 * Set the flag to indicate cache is to be disabled. An attempt
3850 	 * to disable the cache via sd_cache_control() will be made
3851 	 * later during attach once the basic initialization is complete.
3852 	 */
3853 	if (flags & SD_CONF_BSET_NOCACHE) {
3854 		un->un_f_opt_disable_cache = TRUE;
3855 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3856 		    "sd_set_vers1_properties: caching disabled flag set\n");
3857 	}
3858 
3859 	/* CD-specific configuration parameters */
3860 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
3861 		un->un_f_cfg_playmsf_bcd = TRUE;
3862 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3863 		    "sd_set_vers1_properties: playmsf_bcd set\n");
3864 	}
3865 	if (flags & SD_CONF_BSET_READSUB_BCD) {
3866 		un->un_f_cfg_readsub_bcd = TRUE;
3867 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3868 		    "sd_set_vers1_properties: readsub_bcd set\n");
3869 	}
3870 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
3871 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
3872 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3873 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
3874 	}
3875 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
3876 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
3877 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3878 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
3879 	}
3880 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
3881 		un->un_f_cfg_no_read_header = TRUE;
3882 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3883 			    "sd_set_vers1_properties: no_read_header set\n");
3884 	}
3885 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
3886 		un->un_f_cfg_read_cd_xd4 = TRUE;
3887 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3888 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
3889 	}
3890 
3891 	/* Support for devices which do not have valid/unique serial numbers */
3892 	if (flags & SD_CONF_BSET_FAB_DEVID) {
3893 		un->un_f_opt_fab_devid = TRUE;
3894 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3895 		    "sd_set_vers1_properties: fab_devid bit set\n");
3896 	}
3897 
3898 	/* Support for user throttle configuration */
3899 	if (flags & SD_CONF_BSET_THROTTLE) {
3900 		ASSERT(prop_list != NULL);
3901 		un->un_saved_throttle = un->un_throttle =
3902 		    prop_list->sdt_throttle;
3903 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3904 		    "sd_set_vers1_properties: throttle set to %d\n",
3905 		    prop_list->sdt_throttle);
3906 	}
3907 
3908 	/* Set the per disk retry count according to the conf file or table. */
3909 	if (flags & SD_CONF_BSET_NRR_COUNT) {
3910 		ASSERT(prop_list != NULL);
3911 		if (prop_list->sdt_not_rdy_retries) {
3912 			un->un_notready_retry_count =
3913 				prop_list->sdt_not_rdy_retries;
3914 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3915 			    "sd_set_vers1_properties: not ready retry count"
3916 			    " set to %d\n", un->un_notready_retry_count);
3917 		}
3918 	}
3919 
3920 	/* The controller type is reported for generic disk driver ioctls */
3921 	if (flags & SD_CONF_BSET_CTYPE) {
3922 		ASSERT(prop_list != NULL);
3923 		switch (prop_list->sdt_ctype) {
3924 		case CTYPE_CDROM:
3925 			un->un_ctype = prop_list->sdt_ctype;
3926 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3927 			    "sd_set_vers1_properties: ctype set to "
3928 			    "CTYPE_CDROM\n");
3929 			break;
3930 		case CTYPE_CCS:
3931 			un->un_ctype = prop_list->sdt_ctype;
3932 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3933 				"sd_set_vers1_properties: ctype set to "
3934 				"CTYPE_CCS\n");
3935 			break;
3936 		case CTYPE_ROD:		/* RW optical */
3937 			un->un_ctype = prop_list->sdt_ctype;
3938 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3939 			    "sd_set_vers1_properties: ctype set to "
3940 			    "CTYPE_ROD\n");
3941 			break;
3942 		default:
3943 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3944 			    "sd_set_vers1_properties: Could not set "
3945 			    "invalid ctype value (%d)",
3946 			    prop_list->sdt_ctype);
3947 		}
3948 	}
3949 
3950 	/* Purple failover timeout */
3951 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
3952 		ASSERT(prop_list != NULL);
3953 		un->un_busy_retry_count =
3954 			prop_list->sdt_busy_retries;
3955 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3956 		    "sd_set_vers1_properties: "
3957 		    "busy retry count set to %d\n",
3958 		    un->un_busy_retry_count);
3959 	}
3960 
3961 	/* Purple reset retry count */
3962 	if (flags & SD_CONF_BSET_RST_RETRIES) {
3963 		ASSERT(prop_list != NULL);
3964 		un->un_reset_retry_count =
3965 			prop_list->sdt_reset_retries;
3966 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3967 		    "sd_set_vers1_properties: "
3968 		    "reset retry count set to %d\n",
3969 		    un->un_reset_retry_count);
3970 	}
3971 
3972 	/* Purple reservation release timeout */
3973 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
3974 		ASSERT(prop_list != NULL);
3975 		un->un_reserve_release_time =
3976 			prop_list->sdt_reserv_rel_time;
3977 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3978 		    "sd_set_vers1_properties: "
3979 		    "reservation release timeout set to %d\n",
3980 		    un->un_reserve_release_time);
3981 	}
3982 
3983 	/*
3984 	 * Driver flag telling the driver to verify that no commands are pending
3985 	 * for a device before issuing a Test Unit Ready. This is a workaround
3986 	 * for a firmware bug in some Seagate eliteI drives.
3987 	 */
3988 	if (flags & SD_CONF_BSET_TUR_CHECK) {
3989 		un->un_f_cfg_tur_check = TRUE;
3990 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3991 		    "sd_set_vers1_properties: tur queue check set\n");
3992 	}
3993 
3994 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
3995 		un->un_min_throttle = prop_list->sdt_min_throttle;
3996 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
3997 		    "sd_set_vers1_properties: min throttle set to %d\n",
3998 		    un->un_min_throttle);
3999 	}
4000 
4001 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4002 		un->un_f_disksort_disabled =
4003 		    (prop_list->sdt_disk_sort_dis != 0) ?
4004 		    TRUE : FALSE;
4005 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4006 		    "sd_set_vers1_properties: disksort disabled "
4007 		    "flag set to %d\n",
4008 		    prop_list->sdt_disk_sort_dis);
4009 	}
4010 
4011 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4012 		un->un_f_lun_reset_enabled =
4013 		    (prop_list->sdt_lun_reset_enable != 0) ?
4014 		    TRUE : FALSE;
4015 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4016 		    "sd_set_vers1_properties: lun reset enabled "
4017 		    "flag set to %d\n",
4018 		    prop_list->sdt_lun_reset_enable);
4019 	}
4020 
4021 	/*
4022 	 * Validate the throttle values.
4023 	 * If any of the numbers are invalid, set everything to defaults.
4024 	 */
4025 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4026 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4027 	    (un->un_min_throttle > un->un_throttle)) {
4028 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4029 		un->un_min_throttle = sd_min_throttle;
4030 	}
4031 }
4032 
4033 /*
4034  *   Function: sd_is_lsi()
4035  *
4036  *   Description: Check for lsi devices, step throught the static device
4037  *	table to match vid/pid.
4038  *
4039  *   Args: un - ptr to sd_lun
4040  *
4041  *   Notes:  When creating new LSI property, need to add the new LSI property
4042  *		to this function.
4043  */
4044 static void
4045 sd_is_lsi(struct sd_lun *un)
4046 {
4047 	char	*id = NULL;
4048 	int	table_index;
4049 	int	idlen;
4050 	void	*prop;
4051 
4052 	ASSERT(un != NULL);
4053 	for (table_index = 0; table_index < sd_disk_table_size;
4054 	    table_index++) {
4055 		id = sd_disk_table[table_index].device_id;
4056 		idlen = strlen(id);
4057 		if (idlen == 0) {
4058 			continue;
4059 		}
4060 
4061 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4062 			prop = sd_disk_table[table_index].properties;
4063 			if (prop == &lsi_properties ||
4064 			    prop == &lsi_oem_properties ||
4065 			    prop == &lsi_properties_scsi ||
4066 			    prop == &symbios_properties) {
4067 				un->un_f_cfg_is_lsi = TRUE;
4068 			}
4069 			break;
4070 		}
4071 	}
4072 }
4073 
4074 
4075 /*
4076  * The following routines support reading and interpretation of disk labels,
4077  * including Solaris BE (8-slice) vtoc's, Solaris LE (16-slice) vtoc's, and
4078  * fdisk tables.
4079  */
4080 
4081 /*
4082  *    Function: sd_validate_geometry
4083  *
4084  * Description: Read the label from the disk (if present). Update the unit's
4085  *		geometry and vtoc information from the data in the label.
4086  *		Verify that the label is valid.
4087  *
4088  *   Arguments: un - driver soft state (unit) structure
4089  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4090  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4091  *			to use the USCSI "direct" chain and bypass the normal
4092  *			command waitq.
4093  *
4094  * Return Code: 0 - Successful completion
4095  *		EINVAL  - Invalid value in un->un_tgt_blocksize or
4096  *			  un->un_blockcount; or label on disk is corrupted
4097  *			  or unreadable.
4098  *		EACCES  - Reservation conflict at the device.
4099  *		ENOMEM  - Resource allocation error
4100  *		ENOTSUP - geometry not applicable
4101  *
4102  *     Context: Kernel thread only (can sleep).
4103  */
4104 
4105 static int
4106 sd_validate_geometry(struct sd_lun *un, int path_flag)
4107 {
4108 	static	char		labelstring[128];
4109 	static	char		buf[256];
4110 	char	*label		= NULL;
4111 	int	label_error	= 0;
4112 	int	gvalid		= un->un_f_geometry_is_valid;
4113 	int	lbasize;
4114 	uint_t	capacity;
4115 	int	count;
4116 
4117 	ASSERT(un != NULL);
4118 	ASSERT(mutex_owned(SD_MUTEX(un)));
4119 
4120 	/*
4121 	 * If the required values are not valid, then try getting them
4122 	 * once via read capacity. If that fails, then fail this call.
4123 	 * This is necessary with the new mpxio failover behavior in
4124 	 * the T300 where we can get an attach for the inactive path
4125 	 * before the active path. The inactive path fails commands with
4126 	 * sense data of 02,04,88 which happens to the read capacity
4127 	 * before mpxio has had sufficient knowledge to know if it should
4128 	 * force a fail over or not. (Which it won't do at attach anyhow).
4129 	 * If the read capacity at attach time fails, un_tgt_blocksize and
4130 	 * un_blockcount won't be valid.
4131 	 */
4132 	if ((un->un_f_tgt_blocksize_is_valid != TRUE) ||
4133 	    (un->un_f_blockcount_is_valid != TRUE)) {
4134 		uint64_t	cap;
4135 		uint32_t	lbasz;
4136 		int		rval;
4137 
4138 		mutex_exit(SD_MUTEX(un));
4139 		rval = sd_send_scsi_READ_CAPACITY(un, &cap,
4140 		    &lbasz, SD_PATH_DIRECT);
4141 		mutex_enter(SD_MUTEX(un));
4142 		if (rval == 0) {
4143 			/*
4144 			 * The following relies on
4145 			 * sd_send_scsi_READ_CAPACITY never
4146 			 * returning 0 for capacity and/or lbasize.
4147 			 */
4148 			sd_update_block_info(un, lbasz, cap);
4149 		}
4150 
4151 		if ((un->un_f_tgt_blocksize_is_valid != TRUE) ||
4152 		    (un->un_f_blockcount_is_valid != TRUE)) {
4153 			return (EINVAL);
4154 		}
4155 	}
4156 
4157 	/*
4158 	 * Copy the lbasize and capacity so that if they're reset while we're
4159 	 * not holding the SD_MUTEX, we will continue to use valid values
4160 	 * after the SD_MUTEX is reacquired. (4119659)
4161 	 */
4162 	lbasize  = un->un_tgt_blocksize;
4163 	capacity = un->un_blockcount;
4164 
4165 #if defined(_SUNOS_VTOC_16)
4166 	/*
4167 	 * Set up the "whole disk" fdisk partition; this should always
4168 	 * exist, regardless of whether the disk contains an fdisk table
4169 	 * or vtoc.
4170 	 */
4171 	un->un_map[P0_RAW_DISK].dkl_cylno = 0;
4172 	un->un_map[P0_RAW_DISK].dkl_nblk  = capacity;
4173 #endif
4174 
4175 	/*
4176 	 * Refresh the logical and physical geometry caches.
4177 	 * (data from MODE SENSE format/rigid disk geometry pages,
4178 	 * and scsi_ifgetcap("geometry").
4179 	 */
4180 	sd_resync_geom_caches(un, capacity, lbasize, path_flag);
4181 
4182 	label_error = sd_use_efi(un, path_flag);
4183 	if (label_error == 0) {
4184 		/* found a valid EFI label */
4185 		SD_TRACE(SD_LOG_IO_PARTITION, un,
4186 			"sd_validate_geometry: found EFI label\n");
4187 		un->un_solaris_offset = 0;
4188 		un->un_solaris_size = capacity;
4189 		return (ENOTSUP);
4190 	}
4191 	if (un->un_blockcount > DK_MAX_BLOCKS) {
4192 		if (label_error == ESRCH) {
4193 			/*
4194 			 * they've configured a LUN over 1TB, but used
4195 			 * format.dat to restrict format's view of the
4196 			 * capacity to be under 1TB
4197 			 */
4198 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4199 "is >1TB and has a VTOC label: use format(1M) to either decrease the");
4200 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
4201 "size to be < 1TB or relabel the disk with an EFI label");
4202 		} else {
4203 			/* unlabeled disk over 1TB */
4204 			return (ENOTSUP);
4205 		}
4206 	}
4207 	label_error = 0;
4208 
4209 	/*
4210 	 * at this point it is either labeled with a VTOC or it is
4211 	 * under 1TB
4212 	 */
4213 	if (un->un_f_vtoc_label_supported) {
4214 		struct	dk_label *dkl;
4215 		offset_t dkl1;
4216 		offset_t label_addr, real_addr;
4217 		int	rval;
4218 		size_t	buffer_size;
4219 
4220 		/*
4221 		 * Note: This will set up un->un_solaris_size and
4222 		 * un->un_solaris_offset.
4223 		 */
4224 		switch (sd_read_fdisk(un, capacity, lbasize, path_flag)) {
4225 		case SD_CMD_RESERVATION_CONFLICT:
4226 			ASSERT(mutex_owned(SD_MUTEX(un)));
4227 			return (EACCES);
4228 		case SD_CMD_FAILURE:
4229 			ASSERT(mutex_owned(SD_MUTEX(un)));
4230 			return (ENOMEM);
4231 		}
4232 
4233 		if (un->un_solaris_size <= DK_LABEL_LOC) {
4234 			/*
4235 			 * Found fdisk table but no Solaris partition entry,
4236 			 * so don't call sd_uselabel() and don't create
4237 			 * a default label.
4238 			 */
4239 			label_error = 0;
4240 			un->un_f_geometry_is_valid = TRUE;
4241 			goto no_solaris_partition;
4242 		}
4243 		label_addr = (daddr_t)(un->un_solaris_offset + DK_LABEL_LOC);
4244 
4245 		/*
4246 		 * sys_blocksize != tgt_blocksize, need to re-adjust
4247 		 * blkno and save the index to beginning of dk_label
4248 		 */
4249 		real_addr = SD_SYS2TGTBLOCK(un, label_addr);
4250 		buffer_size = SD_REQBYTES2TGTBYTES(un,
4251 		    sizeof (struct dk_label));
4252 
4253 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_validate_geometry: "
4254 		    "label_addr: 0x%x allocation size: 0x%x\n",
4255 		    label_addr, buffer_size);
4256 		dkl = kmem_zalloc(buffer_size, KM_NOSLEEP);
4257 		if (dkl == NULL) {
4258 			return (ENOMEM);
4259 		}
4260 
4261 		mutex_exit(SD_MUTEX(un));
4262 		rval = sd_send_scsi_READ(un, dkl, buffer_size, real_addr,
4263 		    path_flag);
4264 		mutex_enter(SD_MUTEX(un));
4265 
4266 		switch (rval) {
4267 		case 0:
4268 			/*
4269 			 * sd_uselabel will establish that the geometry
4270 			 * is valid.
4271 			 * For sys_blocksize != tgt_blocksize, need
4272 			 * to index into the beginning of dk_label
4273 			 */
4274 			dkl1 = (daddr_t)dkl
4275 				+ SD_TGTBYTEOFFSET(un, label_addr, real_addr);
4276 			if (sd_uselabel(un, (struct dk_label *)(uintptr_t)dkl1,
4277 			    path_flag) != SD_LABEL_IS_VALID) {
4278 				label_error = EINVAL;
4279 			}
4280 			break;
4281 		case EACCES:
4282 			label_error = EACCES;
4283 			break;
4284 		default:
4285 			label_error = EINVAL;
4286 			break;
4287 		}
4288 
4289 		kmem_free(dkl, buffer_size);
4290 
4291 #if defined(_SUNOS_VTOC_8)
4292 		label = (char *)un->un_asciilabel;
4293 #elif defined(_SUNOS_VTOC_16)
4294 		label = (char *)un->un_vtoc.v_asciilabel;
4295 #else
4296 #error "No VTOC format defined."
4297 #endif
4298 	}
4299 
4300 	/*
4301 	 * If a valid label was not found, AND if no reservation conflict
4302 	 * was detected, then go ahead and create a default label (4069506).
4303 	 */
4304 
4305 	if (un->un_f_default_vtoc_supported && (label_error != EACCES)) {
4306 		if (un->un_f_geometry_is_valid == FALSE) {
4307 			sd_build_default_label(un);
4308 		}
4309 		label_error = 0;
4310 	}
4311 
4312 no_solaris_partition:
4313 	if ((!un->un_f_has_removable_media ||
4314 	    (un->un_f_has_removable_media &&
4315 		un->un_mediastate == DKIO_EJECTED)) &&
4316 		(un->un_state == SD_STATE_NORMAL && !gvalid)) {
4317 		/*
4318 		 * Print out a message indicating who and what we are.
4319 		 * We do this only when we happen to really validate the
4320 		 * geometry. We may call sd_validate_geometry() at other
4321 		 * times, e.g., ioctl()'s like Get VTOC in which case we
4322 		 * don't want to print the label.
4323 		 * If the geometry is valid, print the label string,
4324 		 * else print vendor and product info, if available
4325 		 */
4326 		if ((un->un_f_geometry_is_valid == TRUE) && (label != NULL)) {
4327 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "?<%s>\n", label);
4328 		} else {
4329 			mutex_enter(&sd_label_mutex);
4330 			sd_inq_fill(SD_INQUIRY(un)->inq_vid, VIDMAX,
4331 			    labelstring);
4332 			sd_inq_fill(SD_INQUIRY(un)->inq_pid, PIDMAX,
4333 			    &labelstring[64]);
4334 			(void) sprintf(buf, "?Vendor '%s', product '%s'",
4335 			    labelstring, &labelstring[64]);
4336 			if (un->un_f_blockcount_is_valid == TRUE) {
4337 				(void) sprintf(&buf[strlen(buf)],
4338 				    ", %llu %u byte blocks\n",
4339 				    (longlong_t)un->un_blockcount,
4340 				    un->un_tgt_blocksize);
4341 			} else {
4342 				(void) sprintf(&buf[strlen(buf)],
4343 				    ", (unknown capacity)\n");
4344 			}
4345 			SD_INFO(SD_LOG_ATTACH_DETACH, un, buf);
4346 			mutex_exit(&sd_label_mutex);
4347 		}
4348 	}
4349 
4350 #if defined(_SUNOS_VTOC_16)
4351 	/*
4352 	 * If we have valid geometry, set up the remaining fdisk partitions.
4353 	 * Note that dkl_cylno is not used for the fdisk map entries, so
4354 	 * we set it to an entirely bogus value.
4355 	 */
4356 	for (count = 0; count < FD_NUMPART; count++) {
4357 		un->un_map[FDISK_P1 + count].dkl_cylno = -1;
4358 		un->un_map[FDISK_P1 + count].dkl_nblk =
4359 		    un->un_fmap[count].fmap_nblk;
4360 
4361 		un->un_offset[FDISK_P1 + count] =
4362 		    un->un_fmap[count].fmap_start;
4363 	}
4364 #endif
4365 
4366 	for (count = 0; count < NDKMAP; count++) {
4367 #if defined(_SUNOS_VTOC_8)
4368 		struct dk_map *lp  = &un->un_map[count];
4369 		un->un_offset[count] =
4370 		    un->un_g.dkg_nhead * un->un_g.dkg_nsect * lp->dkl_cylno;
4371 #elif defined(_SUNOS_VTOC_16)
4372 		struct dkl_partition *vp = &un->un_vtoc.v_part[count];
4373 
4374 		un->un_offset[count] = vp->p_start + un->un_solaris_offset;
4375 #else
4376 #error "No VTOC format defined."
4377 #endif
4378 	}
4379 
4380 	return (label_error);
4381 }
4382 
4383 
4384 #if defined(_SUNOS_VTOC_16)
4385 /*
4386  * Macro: MAX_BLKS
4387  *
4388  *	This macro is used for table entries where we need to have the largest
4389  *	possible sector value for that head & SPT (sectors per track)
4390  *	combination.  Other entries for some smaller disk sizes are set by
4391  *	convention to match those used by X86 BIOS usage.
4392  */
4393 #define	MAX_BLKS(heads, spt)	UINT16_MAX * heads * spt, heads, spt
4394 
4395 /*
4396  *    Function: sd_convert_geometry
4397  *
4398  * Description: Convert physical geometry into a dk_geom structure. In
4399  *		other words, make sure we don't wrap 16-bit values.
4400  *		e.g. converting from geom_cache to dk_geom
4401  *
4402  *     Context: Kernel thread only
4403  */
4404 static void
4405 sd_convert_geometry(uint64_t capacity, struct dk_geom *un_g)
4406 {
4407 	int i;
4408 	static const struct chs_values {
4409 		uint_t max_cap;		/* Max Capacity for this HS. */
4410 		uint_t nhead;		/* Heads to use. */
4411 		uint_t nsect;		/* SPT to use. */
4412 	} CHS_values[] = {
4413 		{0x00200000,  64, 32},		/* 1GB or smaller disk. */
4414 		{0x01000000, 128, 32},		/* 8GB or smaller disk. */
4415 		{MAX_BLKS(255,  63)},		/* 502.02GB or smaller disk. */
4416 		{MAX_BLKS(255, 126)},		/* .98TB or smaller disk. */
4417 		{DK_MAX_BLOCKS, 255, 189}	/* Max size is just under 1TB */
4418 	};
4419 
4420 	/* Unlabeled SCSI floppy device */
4421 	if (capacity <= 0x1000) {
4422 		un_g->dkg_nhead = 2;
4423 		un_g->dkg_ncyl = 80;
4424 		un_g->dkg_nsect = capacity / (un_g->dkg_nhead * un_g->dkg_ncyl);
4425 		return;
4426 	}
4427 
4428 	/*
4429 	 * For all devices we calculate cylinders using the
4430 	 * heads and sectors we assign based on capacity of the
4431 	 * device.  The table is designed to be compatible with the
4432 	 * way other operating systems lay out fdisk tables for X86
4433 	 * and to insure that the cylinders never exceed 65535 to
4434 	 * prevent problems with X86 ioctls that report geometry.
4435 	 * We use SPT that are multiples of 63, since other OSes that
4436 	 * are not limited to 16-bits for cylinders stop at 63 SPT
4437 	 * we make do by using multiples of 63 SPT.
4438 	 *
4439 	 * Note than capacities greater than or equal to 1TB will simply
4440 	 * get the largest geometry from the table. This should be okay
4441 	 * since disks this large shouldn't be using CHS values anyway.
4442 	 */
4443 	for (i = 0; CHS_values[i].max_cap < capacity &&
4444 	    CHS_values[i].max_cap != DK_MAX_BLOCKS; i++)
4445 		;
4446 
4447 	un_g->dkg_nhead = CHS_values[i].nhead;
4448 	un_g->dkg_nsect = CHS_values[i].nsect;
4449 }
4450 #endif
4451 
4452 
4453 /*
4454  *    Function: sd_resync_geom_caches
4455  *
4456  * Description: (Re)initialize both geometry caches: the virtual geometry
4457  *		information is extracted from the HBA (the "geometry"
4458  *		capability), and the physical geometry cache data is
4459  *		generated by issuing MODE SENSE commands.
4460  *
4461  *   Arguments: un - driver soft state (unit) structure
4462  *		capacity - disk capacity in #blocks
4463  *		lbasize - disk block size in bytes
4464  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4465  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4466  *			to use the USCSI "direct" chain and bypass the normal
4467  *			command waitq.
4468  *
4469  *     Context: Kernel thread only (can sleep).
4470  */
4471 
4472 static void
4473 sd_resync_geom_caches(struct sd_lun *un, int capacity, int lbasize,
4474 	int path_flag)
4475 {
4476 	struct 	geom_cache 	pgeom;
4477 	struct 	geom_cache	*pgeom_p = &pgeom;
4478 	int 	spc;
4479 	unsigned short nhead;
4480 	unsigned short nsect;
4481 
4482 	ASSERT(un != NULL);
4483 	ASSERT(mutex_owned(SD_MUTEX(un)));
4484 
4485 	/*
4486 	 * Ask the controller for its logical geometry.
4487 	 * Note: if the HBA does not support scsi_ifgetcap("geometry"),
4488 	 * then the lgeom cache will be invalid.
4489 	 */
4490 	sd_get_virtual_geometry(un, capacity, lbasize);
4491 
4492 	/*
4493 	 * Initialize the pgeom cache from lgeom, so that if MODE SENSE
4494 	 * doesn't work, DKIOCG_PHYSGEOM can return reasonable values.
4495 	 */
4496 	if (un->un_lgeom.g_nsect == 0 || un->un_lgeom.g_nhead == 0) {
4497 		/*
4498 		 * Note: Perhaps this needs to be more adaptive? The rationale
4499 		 * is that, if there's no HBA geometry from the HBA driver, any
4500 		 * guess is good, since this is the physical geometry. If MODE
4501 		 * SENSE fails this gives a max cylinder size for non-LBA access
4502 		 */
4503 		nhead = 255;
4504 		nsect = 63;
4505 	} else {
4506 		nhead = un->un_lgeom.g_nhead;
4507 		nsect = un->un_lgeom.g_nsect;
4508 	}
4509 
4510 	if (ISCD(un)) {
4511 		pgeom_p->g_nhead = 1;
4512 		pgeom_p->g_nsect = nsect * nhead;
4513 	} else {
4514 		pgeom_p->g_nhead = nhead;
4515 		pgeom_p->g_nsect = nsect;
4516 	}
4517 
4518 	spc = pgeom_p->g_nhead * pgeom_p->g_nsect;
4519 	pgeom_p->g_capacity = capacity;
4520 	pgeom_p->g_ncyl = pgeom_p->g_capacity / spc;
4521 	pgeom_p->g_acyl = 0;
4522 
4523 	/*
4524 	 * Retrieve fresh geometry data from the hardware, stash it
4525 	 * here temporarily before we rebuild the incore label.
4526 	 *
4527 	 * We want to use the MODE SENSE commands to derive the
4528 	 * physical geometry of the device, but if either command
4529 	 * fails, the logical geometry is used as the fallback for
4530 	 * disk label geometry.
4531 	 */
4532 	mutex_exit(SD_MUTEX(un));
4533 	sd_get_physical_geometry(un, pgeom_p, capacity, lbasize, path_flag);
4534 	mutex_enter(SD_MUTEX(un));
4535 
4536 	/*
4537 	 * Now update the real copy while holding the mutex. This
4538 	 * way the global copy is never in an inconsistent state.
4539 	 */
4540 	bcopy(pgeom_p, &un->un_pgeom,  sizeof (un->un_pgeom));
4541 
4542 	SD_INFO(SD_LOG_COMMON, un, "sd_resync_geom_caches: "
4543 	    "(cached from lgeom)\n");
4544 	SD_INFO(SD_LOG_COMMON, un,
4545 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4546 	    un->un_pgeom.g_ncyl, un->un_pgeom.g_acyl,
4547 	    un->un_pgeom.g_nhead, un->un_pgeom.g_nsect);
4548 	SD_INFO(SD_LOG_COMMON, un, "   lbasize: %d; capacity: %ld; "
4549 	    "intrlv: %d; rpm: %d\n", un->un_pgeom.g_secsize,
4550 	    un->un_pgeom.g_capacity, un->un_pgeom.g_intrlv,
4551 	    un->un_pgeom.g_rpm);
4552 }
4553 
4554 
4555 /*
4556  *    Function: sd_read_fdisk
4557  *
4558  * Description: utility routine to read the fdisk table.
4559  *
4560  *   Arguments: un - driver soft state (unit) structure
4561  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4562  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4563  *			to use the USCSI "direct" chain and bypass the normal
4564  *			command waitq.
4565  *
4566  * Return Code: SD_CMD_SUCCESS
4567  *		SD_CMD_FAILURE
4568  *
4569  *     Context: Kernel thread only (can sleep).
4570  */
4571 /* ARGSUSED */
4572 static int
4573 sd_read_fdisk(struct sd_lun *un, uint_t capacity, int lbasize, int path_flag)
4574 {
4575 #if defined(_NO_FDISK_PRESENT)
4576 
4577 	un->un_solaris_offset = 0;
4578 	un->un_solaris_size = capacity;
4579 	bzero(un->un_fmap, sizeof (struct fmap) * FD_NUMPART);
4580 	return (SD_CMD_SUCCESS);
4581 
4582 #elif defined(_FIRMWARE_NEEDS_FDISK)
4583 
4584 	struct ipart	*fdp;
4585 	struct mboot	*mbp;
4586 	struct ipart	fdisk[FD_NUMPART];
4587 	int		i;
4588 	char		sigbuf[2];
4589 	caddr_t		bufp;
4590 	int		uidx;
4591 	int		rval;
4592 	int		lba = 0;
4593 	uint_t		solaris_offset;	/* offset to solaris part. */
4594 	daddr_t		solaris_size;	/* size of solaris partition */
4595 	uint32_t	blocksize;
4596 
4597 	ASSERT(un != NULL);
4598 	ASSERT(mutex_owned(SD_MUTEX(un)));
4599 	ASSERT(un->un_f_tgt_blocksize_is_valid == TRUE);
4600 
4601 	blocksize = un->un_tgt_blocksize;
4602 
4603 	/*
4604 	 * Start off assuming no fdisk table
4605 	 */
4606 	solaris_offset = 0;
4607 	solaris_size   = capacity;
4608 
4609 	mutex_exit(SD_MUTEX(un));
4610 	bufp = kmem_zalloc(blocksize, KM_SLEEP);
4611 	rval = sd_send_scsi_READ(un, bufp, blocksize, 0, path_flag);
4612 	mutex_enter(SD_MUTEX(un));
4613 
4614 	if (rval != 0) {
4615 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
4616 		    "sd_read_fdisk: fdisk read err\n");
4617 		kmem_free(bufp, blocksize);
4618 		return (SD_CMD_FAILURE);
4619 	}
4620 
4621 	mbp = (struct mboot *)bufp;
4622 
4623 	/*
4624 	 * The fdisk table does not begin on a 4-byte boundary within the
4625 	 * master boot record, so we copy it to an aligned structure to avoid
4626 	 * alignment exceptions on some processors.
4627 	 */
4628 	bcopy(&mbp->parts[0], fdisk, sizeof (fdisk));
4629 
4630 	/*
4631 	 * Check for lba support before verifying sig; sig might not be
4632 	 * there, say on a blank disk, but the max_chs mark may still
4633 	 * be present.
4634 	 *
4635 	 * Note: LBA support and BEFs are an x86-only concept but this
4636 	 * code should work OK on SPARC as well.
4637 	 */
4638 
4639 	/*
4640 	 * First, check for lba-access-ok on root node (or prom root node)
4641 	 * if present there, don't need to search fdisk table.
4642 	 */
4643 	if (ddi_getprop(DDI_DEV_T_ANY, ddi_root_node(), 0,
4644 	    "lba-access-ok", 0) != 0) {
4645 		/* All drives do LBA; don't search fdisk table */
4646 		lba = 1;
4647 	} else {
4648 		/* Okay, look for mark in fdisk table */
4649 		for (fdp = fdisk, i = 0; i < FD_NUMPART; i++, fdp++) {
4650 			/* accumulate "lba" value from all partitions */
4651 			lba = (lba || sd_has_max_chs_vals(fdp));
4652 		}
4653 	}
4654 
4655 	if (lba != 0) {
4656 		dev_t dev = sd_make_device(SD_DEVINFO(un));
4657 
4658 		if (ddi_getprop(dev, SD_DEVINFO(un), DDI_PROP_DONTPASS,
4659 		    "lba-access-ok", 0) == 0) {
4660 			/* not found; create it */
4661 			if (ddi_prop_create(dev, SD_DEVINFO(un), 0,
4662 			    "lba-access-ok", (caddr_t)NULL, 0) !=
4663 			    DDI_PROP_SUCCESS) {
4664 				SD_ERROR(SD_LOG_ATTACH_DETACH, un,
4665 				    "sd_read_fdisk: Can't create lba property "
4666 				    "for instance %d\n",
4667 				    ddi_get_instance(SD_DEVINFO(un)));
4668 			}
4669 		}
4670 	}
4671 
4672 	bcopy(&mbp->signature, sigbuf, sizeof (sigbuf));
4673 
4674 	/*
4675 	 * Endian-independent signature check
4676 	 */
4677 	if (((sigbuf[1] & 0xFF) != ((MBB_MAGIC >> 8) & 0xFF)) ||
4678 	    (sigbuf[0] != (MBB_MAGIC & 0xFF))) {
4679 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
4680 		    "sd_read_fdisk: no fdisk\n");
4681 		bzero(un->un_fmap, sizeof (struct fmap) * FD_NUMPART);
4682 		rval = SD_CMD_SUCCESS;
4683 		goto done;
4684 	}
4685 
4686 #ifdef SDDEBUG
4687 	if (sd_level_mask & SD_LOGMASK_INFO) {
4688 		fdp = fdisk;
4689 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_read_fdisk:\n");
4690 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "         relsect    "
4691 		    "numsect         sysid       bootid\n");
4692 		for (i = 0; i < FD_NUMPART; i++, fdp++) {
4693 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4694 			    "    %d:  %8d   %8d     0x%08x     0x%08x\n",
4695 			    i, fdp->relsect, fdp->numsect,
4696 			    fdp->systid, fdp->bootid);
4697 		}
4698 	}
4699 #endif
4700 
4701 	/*
4702 	 * Try to find the unix partition
4703 	 */
4704 	uidx = -1;
4705 	solaris_offset = 0;
4706 	solaris_size   = 0;
4707 
4708 	for (fdp = fdisk, i = 0; i < FD_NUMPART; i++, fdp++) {
4709 		int	relsect;
4710 		int	numsect;
4711 
4712 		if (fdp->numsect == 0) {
4713 			un->un_fmap[i].fmap_start = 0;
4714 			un->un_fmap[i].fmap_nblk  = 0;
4715 			continue;
4716 		}
4717 
4718 		/*
4719 		 * Data in the fdisk table is little-endian.
4720 		 */
4721 		relsect = LE_32(fdp->relsect);
4722 		numsect = LE_32(fdp->numsect);
4723 
4724 		un->un_fmap[i].fmap_start = relsect;
4725 		un->un_fmap[i].fmap_nblk  = numsect;
4726 
4727 		if (fdp->systid != SUNIXOS &&
4728 		    fdp->systid != SUNIXOS2 &&
4729 		    fdp->systid != EFI_PMBR) {
4730 			continue;
4731 		}
4732 
4733 		/*
4734 		 * use the last active solaris partition id found
4735 		 * (there should only be 1 active partition id)
4736 		 *
4737 		 * if there are no active solaris partition id
4738 		 * then use the first inactive solaris partition id
4739 		 */
4740 		if ((uidx == -1) || (fdp->bootid == ACTIVE)) {
4741 			uidx = i;
4742 			solaris_offset = relsect;
4743 			solaris_size   = numsect;
4744 		}
4745 	}
4746 
4747 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "fdisk 0x%x 0x%lx",
4748 	    un->un_solaris_offset, un->un_solaris_size);
4749 
4750 	rval = SD_CMD_SUCCESS;
4751 
4752 done:
4753 
4754 	/*
4755 	 * Clear the VTOC info, only if the Solaris partition entry
4756 	 * has moved, changed size, been deleted, or if the size of
4757 	 * the partition is too small to even fit the label sector.
4758 	 */
4759 	if ((un->un_solaris_offset != solaris_offset) ||
4760 	    (un->un_solaris_size != solaris_size) ||
4761 	    solaris_size <= DK_LABEL_LOC) {
4762 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "fdisk moved 0x%x 0x%lx",
4763 			solaris_offset, solaris_size);
4764 		bzero(&un->un_g, sizeof (struct dk_geom));
4765 		bzero(&un->un_vtoc, sizeof (struct dk_vtoc));
4766 		bzero(&un->un_map, NDKMAP * (sizeof (struct dk_map)));
4767 		un->un_f_geometry_is_valid = FALSE;
4768 	}
4769 	un->un_solaris_offset = solaris_offset;
4770 	un->un_solaris_size = solaris_size;
4771 	kmem_free(bufp, blocksize);
4772 	return (rval);
4773 
4774 #else	/* #elif defined(_FIRMWARE_NEEDS_FDISK) */
4775 #error "fdisk table presence undetermined for this platform."
4776 #endif	/* #if defined(_NO_FDISK_PRESENT) */
4777 }
4778 
4779 
4780 /*
4781  *    Function: sd_get_physical_geometry
4782  *
4783  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4784  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4785  *		target, and use this information to initialize the physical
4786  *		geometry cache specified by pgeom_p.
4787  *
4788  *		MODE SENSE is an optional command, so failure in this case
4789  *		does not necessarily denote an error. We want to use the
4790  *		MODE SENSE commands to derive the physical geometry of the
4791  *		device, but if either command fails, the logical geometry is
4792  *		used as the fallback for disk label geometry.
4793  *
4794  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4795  *		have already been initialized for the current target and
4796  *		that the current values be passed as args so that we don't
4797  *		end up ever trying to use -1 as a valid value. This could
4798  *		happen if either value is reset while we're not holding
4799  *		the mutex.
4800  *
4801  *   Arguments: un - driver soft state (unit) structure
4802  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4803  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4804  *			to use the USCSI "direct" chain and bypass the normal
4805  *			command waitq.
4806  *
4807  *     Context: Kernel thread only (can sleep).
4808  */
4809 
4810 static void
4811 sd_get_physical_geometry(struct sd_lun *un, struct geom_cache *pgeom_p,
4812 	int capacity, int lbasize, int path_flag)
4813 {
4814 	struct	mode_format	*page3p;
4815 	struct	mode_geometry	*page4p;
4816 	struct	mode_header	*headerp;
4817 	int	sector_size;
4818 	int	nsect;
4819 	int	nhead;
4820 	int	ncyl;
4821 	int	intrlv;
4822 	int	spc;
4823 	int	modesense_capacity;
4824 	int	rpm;
4825 	int	bd_len;
4826 	int	mode_header_length;
4827 	uchar_t	*p3bufp;
4828 	uchar_t	*p4bufp;
4829 	int	cdbsize;
4830 
4831 	ASSERT(un != NULL);
4832 	ASSERT(!(mutex_owned(SD_MUTEX(un))));
4833 
4834 	if (un->un_f_blockcount_is_valid != TRUE) {
4835 		return;
4836 	}
4837 
4838 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
4839 		return;
4840 	}
4841 
4842 	if (lbasize == 0) {
4843 		if (ISCD(un)) {
4844 			lbasize = 2048;
4845 		} else {
4846 			lbasize = un->un_sys_blocksize;
4847 		}
4848 	}
4849 	pgeom_p->g_secsize = (unsigned short)lbasize;
4850 
4851 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4852 
4853 	/*
4854 	 * Retrieve MODE SENSE page 3 - Format Device Page
4855 	 */
4856 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4857 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p3bufp,
4858 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag)
4859 	    != 0) {
4860 		SD_ERROR(SD_LOG_COMMON, un,
4861 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4862 		goto page3_exit;
4863 	}
4864 
4865 	/*
4866 	 * Determine size of Block Descriptors in order to locate the mode
4867 	 * page data.  ATAPI devices return 0, SCSI devices should return
4868 	 * MODE_BLK_DESC_LENGTH.
4869 	 */
4870 	headerp = (struct mode_header *)p3bufp;
4871 	if (un->un_f_cfg_is_atapi == TRUE) {
4872 		struct mode_header_grp2 *mhp =
4873 		    (struct mode_header_grp2 *)headerp;
4874 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4875 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4876 	} else {
4877 		mode_header_length = MODE_HEADER_LENGTH;
4878 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4879 	}
4880 
4881 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4882 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4883 		    "received unexpected bd_len of %d, page3\n", bd_len);
4884 		goto page3_exit;
4885 	}
4886 
4887 	page3p = (struct mode_format *)
4888 	    ((caddr_t)headerp + mode_header_length + bd_len);
4889 
4890 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4891 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4892 		    "mode sense pg3 code mismatch %d\n",
4893 		    page3p->mode_page.code);
4894 		goto page3_exit;
4895 	}
4896 
4897 	/*
4898 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4899 	 * complete successfully; otherwise, revert to the logical geometry.
4900 	 * So, we need to save everything in temporary variables.
4901 	 */
4902 	sector_size = BE_16(page3p->data_bytes_sect);
4903 
4904 	/*
4905 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4906 	 */
4907 	if (sector_size == 0) {
4908 		sector_size = (ISCD(un)) ? 2048 : un->un_sys_blocksize;
4909 	} else {
4910 		sector_size &= ~(un->un_sys_blocksize - 1);
4911 	}
4912 
4913 	nsect  = BE_16(page3p->sect_track);
4914 	intrlv = BE_16(page3p->interleave);
4915 
4916 	SD_INFO(SD_LOG_COMMON, un,
4917 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4918 	SD_INFO(SD_LOG_COMMON, un,
4919 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4920 	    page3p->mode_page.code, nsect, sector_size);
4921 	SD_INFO(SD_LOG_COMMON, un,
4922 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4923 	    BE_16(page3p->track_skew),
4924 	    BE_16(page3p->cylinder_skew));
4925 
4926 
4927 	/*
4928 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4929 	 */
4930 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4931 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p4bufp,
4932 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag)
4933 	    != 0) {
4934 		SD_ERROR(SD_LOG_COMMON, un,
4935 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4936 		goto page4_exit;
4937 	}
4938 
4939 	/*
4940 	 * Determine size of Block Descriptors in order to locate the mode
4941 	 * page data.  ATAPI devices return 0, SCSI devices should return
4942 	 * MODE_BLK_DESC_LENGTH.
4943 	 */
4944 	headerp = (struct mode_header *)p4bufp;
4945 	if (un->un_f_cfg_is_atapi == TRUE) {
4946 		struct mode_header_grp2 *mhp =
4947 		    (struct mode_header_grp2 *)headerp;
4948 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4949 	} else {
4950 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4951 	}
4952 
4953 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4954 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4955 		    "received unexpected bd_len of %d, page4\n", bd_len);
4956 		goto page4_exit;
4957 	}
4958 
4959 	page4p = (struct mode_geometry *)
4960 	    ((caddr_t)headerp + mode_header_length + bd_len);
4961 
4962 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4963 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4964 		    "mode sense pg4 code mismatch %d\n",
4965 		    page4p->mode_page.code);
4966 		goto page4_exit;
4967 	}
4968 
4969 	/*
4970 	 * Stash the data now, after we know that both commands completed.
4971 	 */
4972 
4973 	mutex_enter(SD_MUTEX(un));
4974 
4975 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4976 	spc   = nhead * nsect;
4977 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4978 	rpm   = BE_16(page4p->rpm);
4979 
4980 	modesense_capacity = spc * ncyl;
4981 
4982 	SD_INFO(SD_LOG_COMMON, un,
4983 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4984 	SD_INFO(SD_LOG_COMMON, un,
4985 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4986 	SD_INFO(SD_LOG_COMMON, un,
4987 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4988 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4989 	    (void *)pgeom_p, capacity);
4990 
4991 	/*
4992 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4993 	 * the product of C * H * S returned by MODE SENSE >= that returned
4994 	 * by read capacity. This is an idiosyncrasy of the original x86
4995 	 * disk subsystem.
4996 	 */
4997 	if (modesense_capacity >= capacity) {
4998 		SD_INFO(SD_LOG_COMMON, un,
4999 		    "sd_get_physical_geometry: adjusting acyl; "
5000 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5001 		    (modesense_capacity - capacity + spc - 1) / spc);
5002 		if (sector_size != 0) {
5003 			/* 1243403: NEC D38x7 drives don't support sec size */
5004 			pgeom_p->g_secsize = (unsigned short)sector_size;
5005 		}
5006 		pgeom_p->g_nsect    = (unsigned short)nsect;
5007 		pgeom_p->g_nhead    = (unsigned short)nhead;
5008 		pgeom_p->g_capacity = capacity;
5009 		pgeom_p->g_acyl	    =
5010 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5011 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5012 	}
5013 
5014 	pgeom_p->g_rpm    = (unsigned short)rpm;
5015 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5016 
5017 	SD_INFO(SD_LOG_COMMON, un,
5018 	    "sd_get_physical_geometry: mode sense geometry:\n");
5019 	SD_INFO(SD_LOG_COMMON, un,
5020 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5021 	    nsect, sector_size, intrlv);
5022 	SD_INFO(SD_LOG_COMMON, un,
5023 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5024 	    nhead, ncyl, rpm, modesense_capacity);
5025 	SD_INFO(SD_LOG_COMMON, un,
5026 	    "sd_get_physical_geometry: (cached)\n");
5027 	SD_INFO(SD_LOG_COMMON, un,
5028 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5029 	    un->un_pgeom.g_ncyl,  un->un_pgeom.g_acyl,
5030 	    un->un_pgeom.g_nhead, un->un_pgeom.g_nsect);
5031 	SD_INFO(SD_LOG_COMMON, un,
5032 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5033 	    un->un_pgeom.g_secsize, un->un_pgeom.g_capacity,
5034 	    un->un_pgeom.g_intrlv, un->un_pgeom.g_rpm);
5035 
5036 	mutex_exit(SD_MUTEX(un));
5037 
5038 page4_exit:
5039 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5040 page3_exit:
5041 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5042 }
5043 
5044 
5045 /*
5046  *    Function: sd_get_virtual_geometry
5047  *
5048  * Description: Ask the controller to tell us about the target device.
5049  *
5050  *   Arguments: un - pointer to softstate
5051  *		capacity - disk capacity in #blocks
5052  *		lbasize - disk block size in bytes
5053  *
5054  *     Context: Kernel thread only
5055  */
5056 
5057 static void
5058 sd_get_virtual_geometry(struct sd_lun *un, int capacity, int lbasize)
5059 {
5060 	struct	geom_cache 	*lgeom_p = &un->un_lgeom;
5061 	uint_t	geombuf;
5062 	int	spc;
5063 
5064 	ASSERT(un != NULL);
5065 	ASSERT(mutex_owned(SD_MUTEX(un)));
5066 
5067 	mutex_exit(SD_MUTEX(un));
5068 
5069 	/* Set sector size, and total number of sectors */
5070 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5071 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5072 
5073 	/* Let the HBA tell us its geometry */
5074 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5075 
5076 	mutex_enter(SD_MUTEX(un));
5077 
5078 	/* A value of -1 indicates an undefined "geometry" property */
5079 	if (geombuf == (-1)) {
5080 		return;
5081 	}
5082 
5083 	/* Initialize the logical geometry cache. */
5084 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5085 	lgeom_p->g_nsect   = geombuf & 0xffff;
5086 	lgeom_p->g_secsize = un->un_sys_blocksize;
5087 
5088 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5089 
5090 	/*
5091 	 * Note: The driver originally converted the capacity value from
5092 	 * target blocks to system blocks. However, the capacity value passed
5093 	 * to this routine is already in terms of system blocks (this scaling
5094 	 * is done when the READ CAPACITY command is issued and processed).
5095 	 * This 'error' may have gone undetected because the usage of g_ncyl
5096 	 * (which is based upon g_capacity) is very limited within the driver
5097 	 */
5098 	lgeom_p->g_capacity = capacity;
5099 
5100 	/*
5101 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5102 	 * hba may return zero values if the device has been removed.
5103 	 */
5104 	if (spc == 0) {
5105 		lgeom_p->g_ncyl = 0;
5106 	} else {
5107 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5108 	}
5109 	lgeom_p->g_acyl = 0;
5110 
5111 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5112 	SD_INFO(SD_LOG_COMMON, un,
5113 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5114 	    un->un_lgeom.g_ncyl,  un->un_lgeom.g_acyl,
5115 	    un->un_lgeom.g_nhead, un->un_lgeom.g_nsect);
5116 	SD_INFO(SD_LOG_COMMON, un, "   lbasize: %d; capacity: %ld; "
5117 	    "intrlv: %d; rpm: %d\n", un->un_lgeom.g_secsize,
5118 	    un->un_lgeom.g_capacity, un->un_lgeom.g_intrlv, un->un_lgeom.g_rpm);
5119 }
5120 
5121 
5122 /*
5123  *    Function: sd_update_block_info
5124  *
5125  * Description: Calculate a byte count to sector count bitshift value
5126  *		from sector size.
5127  *
5128  *   Arguments: un: unit struct.
5129  *		lbasize: new target sector size
5130  *		capacity: new target capacity, ie. block count
5131  *
5132  *     Context: Kernel thread context
5133  */
5134 
5135 static void
5136 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5137 {
5138 	if (lbasize != 0) {
5139 		un->un_tgt_blocksize = lbasize;
5140 		un->un_f_tgt_blocksize_is_valid	= TRUE;
5141 	}
5142 
5143 	if (capacity != 0) {
5144 		un->un_blockcount		= capacity;
5145 		un->un_f_blockcount_is_valid	= TRUE;
5146 	}
5147 }
5148 
5149 
5150 static void
5151 sd_swap_efi_gpt(efi_gpt_t *e)
5152 {
5153 	_NOTE(ASSUMING_PROTECTED(*e))
5154 	e->efi_gpt_Signature = LE_64(e->efi_gpt_Signature);
5155 	e->efi_gpt_Revision = LE_32(e->efi_gpt_Revision);
5156 	e->efi_gpt_HeaderSize = LE_32(e->efi_gpt_HeaderSize);
5157 	e->efi_gpt_HeaderCRC32 = LE_32(e->efi_gpt_HeaderCRC32);
5158 	e->efi_gpt_MyLBA = LE_64(e->efi_gpt_MyLBA);
5159 	e->efi_gpt_AlternateLBA = LE_64(e->efi_gpt_AlternateLBA);
5160 	e->efi_gpt_FirstUsableLBA = LE_64(e->efi_gpt_FirstUsableLBA);
5161 	e->efi_gpt_LastUsableLBA = LE_64(e->efi_gpt_LastUsableLBA);
5162 	UUID_LE_CONVERT(e->efi_gpt_DiskGUID, e->efi_gpt_DiskGUID);
5163 	e->efi_gpt_PartitionEntryLBA = LE_64(e->efi_gpt_PartitionEntryLBA);
5164 	e->efi_gpt_NumberOfPartitionEntries =
5165 	    LE_32(e->efi_gpt_NumberOfPartitionEntries);
5166 	e->efi_gpt_SizeOfPartitionEntry =
5167 	    LE_32(e->efi_gpt_SizeOfPartitionEntry);
5168 	e->efi_gpt_PartitionEntryArrayCRC32 =
5169 	    LE_32(e->efi_gpt_PartitionEntryArrayCRC32);
5170 }
5171 
5172 static void
5173 sd_swap_efi_gpe(int nparts, efi_gpe_t *p)
5174 {
5175 	int i;
5176 
5177 	_NOTE(ASSUMING_PROTECTED(*p))
5178 	for (i = 0; i < nparts; i++) {
5179 		UUID_LE_CONVERT(p[i].efi_gpe_PartitionTypeGUID,
5180 		    p[i].efi_gpe_PartitionTypeGUID);
5181 		p[i].efi_gpe_StartingLBA = LE_64(p[i].efi_gpe_StartingLBA);
5182 		p[i].efi_gpe_EndingLBA = LE_64(p[i].efi_gpe_EndingLBA);
5183 		/* PartitionAttrs */
5184 	}
5185 }
5186 
5187 static int
5188 sd_validate_efi(efi_gpt_t *labp)
5189 {
5190 	if (labp->efi_gpt_Signature != EFI_SIGNATURE)
5191 		return (EINVAL);
5192 	/* at least 96 bytes in this version of the spec. */
5193 	if (sizeof (efi_gpt_t) - sizeof (labp->efi_gpt_Reserved2) >
5194 	    labp->efi_gpt_HeaderSize)
5195 		return (EINVAL);
5196 	/* this should be 128 bytes */
5197 	if (labp->efi_gpt_SizeOfPartitionEntry != sizeof (efi_gpe_t))
5198 		return (EINVAL);
5199 	return (0);
5200 }
5201 
5202 static int
5203 sd_use_efi(struct sd_lun *un, int path_flag)
5204 {
5205 	int		i;
5206 	int		rval = 0;
5207 	efi_gpe_t	*partitions;
5208 	uchar_t		*buf;
5209 	uint_t		lbasize;
5210 	uint64_t	cap;
5211 	uint_t		nparts;
5212 	diskaddr_t	gpe_lba;
5213 
5214 	ASSERT(mutex_owned(SD_MUTEX(un)));
5215 	lbasize = un->un_tgt_blocksize;
5216 
5217 	mutex_exit(SD_MUTEX(un));
5218 
5219 	buf = kmem_zalloc(EFI_MIN_ARRAY_SIZE, KM_SLEEP);
5220 
5221 	if (un->un_tgt_blocksize != un->un_sys_blocksize) {
5222 		rval = EINVAL;
5223 		goto done_err;
5224 	}
5225 
5226 	rval = sd_send_scsi_READ(un, buf, lbasize, 0, path_flag);
5227 	if (rval) {
5228 		goto done_err;
5229 	}
5230 	if (((struct dk_label *)buf)->dkl_magic == DKL_MAGIC) {
5231 		/* not ours */
5232 		rval = ESRCH;
5233 		goto done_err;
5234 	}
5235 
5236 	rval = sd_send_scsi_READ(un, buf, lbasize, 1, path_flag);
5237 	if (rval) {
5238 		goto done_err;
5239 	}
5240 	sd_swap_efi_gpt((efi_gpt_t *)buf);
5241 
5242 	if ((rval = sd_validate_efi((efi_gpt_t *)buf)) != 0) {
5243 		/*
5244 		 * Couldn't read the primary, try the backup.  Our
5245 		 * capacity at this point could be based on CHS, so
5246 		 * check what the device reports.
5247 		 */
5248 		rval = sd_send_scsi_READ_CAPACITY(un, &cap, &lbasize,
5249 		    path_flag);
5250 		if (rval) {
5251 			goto done_err;
5252 		}
5253 
5254 		/*
5255 		 * The MMC standard allows READ CAPACITY to be
5256 		 * inaccurate by a bounded amount (in the interest of
5257 		 * response latency).  As a result, failed READs are
5258 		 * commonplace (due to the reading of metadata and not
5259 		 * data). Depending on the per-Vendor/drive Sense data,
5260 		 * the failed READ can cause many (unnecessary) retries.
5261 		 */
5262 		if ((rval = sd_send_scsi_READ(un, buf, lbasize,
5263 		    cap - 1, (ISCD(un)) ? SD_PATH_DIRECT_PRIORITY :
5264 			path_flag)) != 0) {
5265 				goto done_err;
5266 		}
5267 
5268 		sd_swap_efi_gpt((efi_gpt_t *)buf);
5269 		if ((rval = sd_validate_efi((efi_gpt_t *)buf)) != 0)
5270 			goto done_err;
5271 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5272 		    "primary label corrupt; using backup\n");
5273 	}
5274 
5275 	nparts = ((efi_gpt_t *)buf)->efi_gpt_NumberOfPartitionEntries;
5276 	gpe_lba = ((efi_gpt_t *)buf)->efi_gpt_PartitionEntryLBA;
5277 
5278 	rval = sd_send_scsi_READ(un, buf, EFI_MIN_ARRAY_SIZE, gpe_lba,
5279 	    path_flag);
5280 	if (rval) {
5281 		goto done_err;
5282 	}
5283 	partitions = (efi_gpe_t *)buf;
5284 
5285 	if (nparts > MAXPART) {
5286 		nparts = MAXPART;
5287 	}
5288 	sd_swap_efi_gpe(nparts, partitions);
5289 
5290 	mutex_enter(SD_MUTEX(un));
5291 
5292 	/* Fill in partition table. */
5293 	for (i = 0; i < nparts; i++) {
5294 		if (partitions->efi_gpe_StartingLBA != 0 ||
5295 		    partitions->efi_gpe_EndingLBA != 0) {
5296 			un->un_map[i].dkl_cylno =
5297 			    partitions->efi_gpe_StartingLBA;
5298 			un->un_map[i].dkl_nblk =
5299 			    partitions->efi_gpe_EndingLBA -
5300 			    partitions->efi_gpe_StartingLBA + 1;
5301 			un->un_offset[i] =
5302 			    partitions->efi_gpe_StartingLBA;
5303 		}
5304 		if (i == WD_NODE) {
5305 			/*
5306 			 * minor number 7 corresponds to the whole disk
5307 			 */
5308 			un->un_map[i].dkl_cylno = 0;
5309 			un->un_map[i].dkl_nblk = un->un_blockcount;
5310 			un->un_offset[i] = 0;
5311 		}
5312 		partitions++;
5313 	}
5314 	un->un_solaris_offset = 0;
5315 	un->un_solaris_size = cap;
5316 	un->un_f_geometry_is_valid = TRUE;
5317 	kmem_free(buf, EFI_MIN_ARRAY_SIZE);
5318 	return (0);
5319 
5320 done_err:
5321 	kmem_free(buf, EFI_MIN_ARRAY_SIZE);
5322 	mutex_enter(SD_MUTEX(un));
5323 	/*
5324 	 * if we didn't find something that could look like a VTOC
5325 	 * and the disk is over 1TB, we know there isn't a valid label.
5326 	 * Otherwise let sd_uselabel decide what to do.  We only
5327 	 * want to invalidate this if we're certain the label isn't
5328 	 * valid because sd_prop_op will now fail, which in turn
5329 	 * causes things like opens and stats on the partition to fail.
5330 	 */
5331 	if ((un->un_blockcount > DK_MAX_BLOCKS) && (rval != ESRCH)) {
5332 		un->un_f_geometry_is_valid = FALSE;
5333 	}
5334 	return (rval);
5335 }
5336 
5337 
5338 /*
5339  *    Function: sd_uselabel
5340  *
5341  * Description: Validate the disk label and update the relevant data (geometry,
5342  *		partition, vtoc, and capacity data) in the sd_lun struct.
5343  *		Marks the geometry of the unit as being valid.
5344  *
5345  *   Arguments: un: unit struct.
5346  *		dk_label: disk label
5347  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
5348  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
5349  *			to use the USCSI "direct" chain and bypass the normal
5350  *			command waitq.
5351  *
5352  * Return Code: SD_LABEL_IS_VALID: Label read from disk is OK; geometry,
5353  *		partition, vtoc, and capacity data are good.
5354  *
5355  *		SD_LABEL_IS_INVALID: Magic number or checksum error in the
5356  *		label; or computed capacity does not jibe with capacity
5357  *		reported from the READ CAPACITY command.
5358  *
5359  *     Context: Kernel thread only (can sleep).
5360  */
5361 
5362 static int
5363 sd_uselabel(struct sd_lun *un, struct dk_label *labp, int path_flag)
5364 {
5365 	short	*sp;
5366 	short	sum;
5367 	short	count;
5368 	int	label_error = SD_LABEL_IS_VALID;
5369 	int	i;
5370 	int	capacity;
5371 	int	part_end;
5372 	int	track_capacity;
5373 	int	err;
5374 #if defined(_SUNOS_VTOC_16)
5375 	struct	dkl_partition	*vpartp;
5376 #endif
5377 	ASSERT(un != NULL);
5378 	ASSERT(mutex_owned(SD_MUTEX(un)));
5379 
5380 	/* Validate the magic number of the label. */
5381 	if (labp->dkl_magic != DKL_MAGIC) {
5382 #if defined(__sparc)
5383 		if ((un->un_state == SD_STATE_NORMAL) &&
5384 			un->un_f_vtoc_errlog_supported) {
5385 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5386 			    "Corrupt label; wrong magic number\n");
5387 		}
5388 #endif
5389 		return (SD_LABEL_IS_INVALID);
5390 	}
5391 
5392 	/* Validate the checksum of the label. */
5393 	sp  = (short *)labp;
5394 	sum = 0;
5395 	count = sizeof (struct dk_label) / sizeof (short);
5396 	while (count--)	 {
5397 		sum ^= *sp++;
5398 	}
5399 
5400 	if (sum != 0) {
5401 #if	defined(_SUNOS_VTOC_16)
5402 		if ((un->un_state == SD_STATE_NORMAL) && !ISCD(un)) {
5403 #elif defined(_SUNOS_VTOC_8)
5404 		if ((un->un_state == SD_STATE_NORMAL) &&
5405 		    un->un_f_vtoc_errlog_supported) {
5406 #endif
5407 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5408 			    "Corrupt label - label checksum failed\n");
5409 		}
5410 		return (SD_LABEL_IS_INVALID);
5411 	}
5412 
5413 
5414 	/*
5415 	 * Fill in geometry structure with data from label.
5416 	 */
5417 	bzero(&un->un_g, sizeof (struct dk_geom));
5418 	un->un_g.dkg_ncyl   = labp->dkl_ncyl;
5419 	un->un_g.dkg_acyl   = labp->dkl_acyl;
5420 	un->un_g.dkg_bcyl   = 0;
5421 	un->un_g.dkg_nhead  = labp->dkl_nhead;
5422 	un->un_g.dkg_nsect  = labp->dkl_nsect;
5423 	un->un_g.dkg_intrlv = labp->dkl_intrlv;
5424 
5425 #if defined(_SUNOS_VTOC_8)
5426 	un->un_g.dkg_gap1   = labp->dkl_gap1;
5427 	un->un_g.dkg_gap2   = labp->dkl_gap2;
5428 	un->un_g.dkg_bhead  = labp->dkl_bhead;
5429 #endif
5430 #if defined(_SUNOS_VTOC_16)
5431 	un->un_dkg_skew = labp->dkl_skew;
5432 #endif
5433 
5434 #if defined(__i386) || defined(__amd64)
5435 	un->un_g.dkg_apc = labp->dkl_apc;
5436 #endif
5437 
5438 	/*
5439 	 * Currently we rely on the values in the label being accurate. If
5440 	 * dlk_rpm or dlk_pcly are zero in the label, use a default value.
5441 	 *
5442 	 * Note: In the future a MODE SENSE may be used to retrieve this data,
5443 	 * although this command is optional in SCSI-2.
5444 	 */
5445 	un->un_g.dkg_rpm  = (labp->dkl_rpm  != 0) ? labp->dkl_rpm  : 3600;
5446 	un->un_g.dkg_pcyl = (labp->dkl_pcyl != 0) ? labp->dkl_pcyl :
5447 	    (un->un_g.dkg_ncyl + un->un_g.dkg_acyl);
5448 
5449 	/*
5450 	 * The Read and Write reinstruct values may not be valid
5451 	 * for older disks.
5452 	 */
5453 	un->un_g.dkg_read_reinstruct  = labp->dkl_read_reinstruct;
5454 	un->un_g.dkg_write_reinstruct = labp->dkl_write_reinstruct;
5455 
5456 	/* Fill in partition table. */
5457 #if defined(_SUNOS_VTOC_8)
5458 	for (i = 0; i < NDKMAP; i++) {
5459 		un->un_map[i].dkl_cylno = labp->dkl_map[i].dkl_cylno;
5460 		un->un_map[i].dkl_nblk  = labp->dkl_map[i].dkl_nblk;
5461 	}
5462 #endif
5463 #if  defined(_SUNOS_VTOC_16)
5464 	vpartp		= labp->dkl_vtoc.v_part;
5465 	track_capacity	= labp->dkl_nhead * labp->dkl_nsect;
5466 
5467 	/* Prevent divide by zero */
5468 	if (track_capacity == 0) {
5469 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5470 		    "Corrupt label - zero nhead or nsect value\n");
5471 
5472 		return (SD_LABEL_IS_INVALID);
5473 	}
5474 
5475 	for (i = 0; i < NDKMAP; i++, vpartp++) {
5476 		un->un_map[i].dkl_cylno = vpartp->p_start / track_capacity;
5477 		un->un_map[i].dkl_nblk  = vpartp->p_size;
5478 	}
5479 #endif
5480 
5481 	/* Fill in VTOC Structure. */
5482 	bcopy(&labp->dkl_vtoc, &un->un_vtoc, sizeof (struct dk_vtoc));
5483 #if defined(_SUNOS_VTOC_8)
5484 	/*
5485 	 * The 8-slice vtoc does not include the ascii label; save it into
5486 	 * the device's soft state structure here.
5487 	 */
5488 	bcopy(labp->dkl_asciilabel, un->un_asciilabel, LEN_DKL_ASCII);
5489 #endif
5490 
5491 	/* Now look for a valid capacity. */
5492 	track_capacity	= (un->un_g.dkg_nhead * un->un_g.dkg_nsect);
5493 	capacity	= (un->un_g.dkg_ncyl  * track_capacity);
5494 
5495 	if (un->un_g.dkg_acyl) {
5496 #if defined(__i386) || defined(__amd64)
5497 		/* we may have > 1 alts cylinder */
5498 		capacity += (track_capacity * un->un_g.dkg_acyl);
5499 #else
5500 		capacity += track_capacity;
5501 #endif
5502 	}
5503 
5504 	/*
5505 	 * Force check here to ensure the computed capacity is valid.
5506 	 * If capacity is zero, it indicates an invalid label and
5507 	 * we should abort updating the relevant data then.
5508 	 */
5509 	if (capacity == 0) {
5510 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5511 		    "Corrupt label - no valid capacity could be retrieved\n");
5512 
5513 		return (SD_LABEL_IS_INVALID);
5514 	}
5515 
5516 	/* Mark the geometry as valid. */
5517 	un->un_f_geometry_is_valid = TRUE;
5518 
5519 	/*
5520 	 * At this point, un->un_blockcount should contain valid data from
5521 	 * the READ CAPACITY command.
5522 	 */
5523 	if (un->un_f_blockcount_is_valid != TRUE) {
5524 		/*
5525 		 * We have a situation where the target didn't give us a good
5526 		 * READ CAPACITY value, yet there appears to be a valid label.
5527 		 * In this case, we'll fake the capacity.
5528 		 */
5529 		un->un_blockcount = capacity;
5530 		un->un_f_blockcount_is_valid = TRUE;
5531 		goto done;
5532 	}
5533 
5534 
5535 	if ((capacity <= un->un_blockcount) ||
5536 	    (un->un_state != SD_STATE_NORMAL)) {
5537 #if defined(_SUNOS_VTOC_8)
5538 		/*
5539 		 * We can't let this happen on drives that are subdivided
5540 		 * into logical disks (i.e., that have an fdisk table).
5541 		 * The un_blockcount field should always hold the full media
5542 		 * size in sectors, period.  This code would overwrite
5543 		 * un_blockcount with the size of the Solaris fdisk partition.
5544 		 */
5545 		SD_ERROR(SD_LOG_COMMON, un,
5546 		    "sd_uselabel: Label %d blocks; Drive %d blocks\n",
5547 		    capacity, un->un_blockcount);
5548 		un->un_blockcount = capacity;
5549 		un->un_f_blockcount_is_valid = TRUE;
5550 #endif	/* defined(_SUNOS_VTOC_8) */
5551 		goto done;
5552 	}
5553 
5554 	if (ISCD(un)) {
5555 		/* For CDROMs, we trust that the data in the label is OK. */
5556 #if defined(_SUNOS_VTOC_8)
5557 		for (i = 0; i < NDKMAP; i++) {
5558 			part_end = labp->dkl_nhead * labp->dkl_nsect *
5559 			    labp->dkl_map[i].dkl_cylno +
5560 			    labp->dkl_map[i].dkl_nblk  - 1;
5561 
5562 			if ((labp->dkl_map[i].dkl_nblk) &&
5563 			    (part_end > un->un_blockcount)) {
5564 				un->un_f_geometry_is_valid = FALSE;
5565 				break;
5566 			}
5567 		}
5568 #endif
5569 #if defined(_SUNOS_VTOC_16)
5570 		vpartp = &(labp->dkl_vtoc.v_part[0]);
5571 		for (i = 0; i < NDKMAP; i++, vpartp++) {
5572 			part_end = vpartp->p_start + vpartp->p_size;
5573 			if ((vpartp->p_size > 0) &&
5574 			    (part_end > un->un_blockcount)) {
5575 				un->un_f_geometry_is_valid = FALSE;
5576 				break;
5577 			}
5578 		}
5579 #endif
5580 	} else {
5581 		uint64_t t_capacity;
5582 		uint32_t t_lbasize;
5583 
5584 		mutex_exit(SD_MUTEX(un));
5585 		err = sd_send_scsi_READ_CAPACITY(un, &t_capacity, &t_lbasize,
5586 		    path_flag);
5587 		ASSERT(t_capacity <= DK_MAX_BLOCKS);
5588 		mutex_enter(SD_MUTEX(un));
5589 
5590 		if (err == 0) {
5591 			sd_update_block_info(un, t_lbasize, t_capacity);
5592 		}
5593 
5594 		if (capacity > un->un_blockcount) {
5595 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5596 			    "Corrupt label - bad geometry\n");
5597 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
5598 			    "Label says %u blocks; Drive says %llu blocks\n",
5599 			    capacity, (unsigned long long)un->un_blockcount);
5600 			un->un_f_geometry_is_valid = FALSE;
5601 			label_error = SD_LABEL_IS_INVALID;
5602 		}
5603 	}
5604 
5605 done:
5606 
5607 	SD_INFO(SD_LOG_COMMON, un, "sd_uselabel: (label geometry)\n");
5608 	SD_INFO(SD_LOG_COMMON, un,
5609 	    "   ncyl: %d; acyl: %d; nhead: %d; nsect: %d\n",
5610 	    un->un_g.dkg_ncyl,  un->un_g.dkg_acyl,
5611 	    un->un_g.dkg_nhead, un->un_g.dkg_nsect);
5612 	SD_INFO(SD_LOG_COMMON, un,
5613 	    "   lbasize: %d; capacity: %d; intrlv: %d; rpm: %d\n",
5614 	    un->un_tgt_blocksize, un->un_blockcount,
5615 	    un->un_g.dkg_intrlv, un->un_g.dkg_rpm);
5616 	SD_INFO(SD_LOG_COMMON, un, "   wrt_reinstr: %d; rd_reinstr: %d\n",
5617 	    un->un_g.dkg_write_reinstruct, un->un_g.dkg_read_reinstruct);
5618 
5619 	ASSERT(mutex_owned(SD_MUTEX(un)));
5620 
5621 	return (label_error);
5622 }
5623 
5624 
5625 /*
5626  *    Function: sd_build_default_label
5627  *
5628  * Description: Generate a default label for those devices that do not have
5629  *		one, e.g., new media, removable cartridges, etc..
5630  *
5631  *     Context: Kernel thread only
5632  */
5633 
5634 static void
5635 sd_build_default_label(struct sd_lun *un)
5636 {
5637 #if defined(_SUNOS_VTOC_16)
5638 	uint_t	phys_spc;
5639 	uint_t	disksize;
5640 	struct	dk_geom un_g;
5641 #endif
5642 
5643 	ASSERT(un != NULL);
5644 	ASSERT(mutex_owned(SD_MUTEX(un)));
5645 
5646 #if defined(_SUNOS_VTOC_8)
5647 	/*
5648 	 * Note: This is a legacy check for non-removable devices on VTOC_8
5649 	 * only. This may be a valid check for VTOC_16 as well.
5650 	 * Once we understand why there is this difference between SPARC and
5651 	 * x86 platform, we could remove this legacy check.
5652 	 */
5653 	ASSERT(un->un_f_default_vtoc_supported);
5654 #endif
5655 
5656 	bzero(&un->un_g, sizeof (struct dk_geom));
5657 	bzero(&un->un_vtoc, sizeof (struct dk_vtoc));
5658 	bzero(&un->un_map, NDKMAP * (sizeof (struct dk_map)));
5659 
5660 #if defined(_SUNOS_VTOC_8)
5661 
5662 	/*
5663 	 * It's a REMOVABLE media, therefore no label (on sparc, anyway).
5664 	 * But it is still necessary to set up various geometry information,
5665 	 * and we are doing this here.
5666 	 */
5667 
5668 	/*
5669 	 * For the rpm, we use the minimum for the disk.  For the head, cyl,
5670 	 * and number of sector per track, if the capacity <= 1GB, head = 64,
5671 	 * sect = 32.  else head = 255, sect 63 Note: the capacity should be
5672 	 * equal to C*H*S values.  This will cause some truncation of size due
5673 	 * to round off errors. For CD-ROMs, this truncation can have adverse
5674 	 * side effects, so returning ncyl and nhead as 1. The nsect will
5675 	 * overflow for most of CD-ROMs as nsect is of type ushort. (4190569)
5676 	 */
5677 	if (ISCD(un)) {
5678 		/*
5679 		 * Preserve the old behavior for non-writable
5680 		 * medias. Since dkg_nsect is a ushort, it
5681 		 * will lose bits as cdroms have more than
5682 		 * 65536 sectors. So if we recalculate
5683 		 * capacity, it will become much shorter.
5684 		 * But the dkg_* information is not
5685 		 * used for CDROMs so it is OK. But for
5686 		 * Writable CDs we need this information
5687 		 * to be valid (for newfs say). So we
5688 		 * make nsect and nhead > 1 that way
5689 		 * nsect can still stay within ushort limit
5690 		 * without losing any bits.
5691 		 */
5692 		if (un->un_f_mmc_writable_media == TRUE) {
5693 			un->un_g.dkg_nhead = 64;
5694 			un->un_g.dkg_nsect = 32;
5695 			un->un_g.dkg_ncyl = un->un_blockcount / (64 * 32);
5696 			un->un_blockcount = un->un_g.dkg_ncyl *
5697 			    un->un_g.dkg_nhead * un->un_g.dkg_nsect;
5698 		} else {
5699 			un->un_g.dkg_ncyl  = 1;
5700 			un->un_g.dkg_nhead = 1;
5701 			un->un_g.dkg_nsect = un->un_blockcount;
5702 		}
5703 	} else {
5704 		if (un->un_blockcount <= 0x1000) {
5705 			/* unlabeled SCSI floppy device */
5706 			un->un_g.dkg_nhead = 2;
5707 			un->un_g.dkg_ncyl = 80;
5708 			un->un_g.dkg_nsect = un->un_blockcount / (2 * 80);
5709 		} else if (un->un_blockcount <= 0x200000) {
5710 			un->un_g.dkg_nhead = 64;
5711 			un->un_g.dkg_nsect = 32;
5712 			un->un_g.dkg_ncyl  = un->un_blockcount / (64 * 32);
5713 		} else {
5714 			un->un_g.dkg_nhead = 255;
5715 			un->un_g.dkg_nsect = 63;
5716 			un->un_g.dkg_ncyl  = un->un_blockcount / (255 * 63);
5717 		}
5718 		un->un_blockcount =
5719 		    un->un_g.dkg_ncyl * un->un_g.dkg_nhead * un->un_g.dkg_nsect;
5720 	}
5721 
5722 	un->un_g.dkg_acyl	= 0;
5723 	un->un_g.dkg_bcyl	= 0;
5724 	un->un_g.dkg_rpm	= 200;
5725 	un->un_asciilabel[0]	= '\0';
5726 	un->un_g.dkg_pcyl	= un->un_g.dkg_ncyl;
5727 
5728 	un->un_map[0].dkl_cylno = 0;
5729 	un->un_map[0].dkl_nblk  = un->un_blockcount;
5730 	un->un_map[2].dkl_cylno = 0;
5731 	un->un_map[2].dkl_nblk  = un->un_blockcount;
5732 
5733 #elif defined(_SUNOS_VTOC_16)
5734 
5735 	if (un->un_solaris_size == 0) {
5736 		/*
5737 		 * Got fdisk table but no solaris entry therefore
5738 		 * don't create a default label
5739 		 */
5740 		un->un_f_geometry_is_valid = TRUE;
5741 		return;
5742 	}
5743 
5744 	/*
5745 	 * For CDs we continue to use the physical geometry to calculate
5746 	 * number of cylinders. All other devices must convert the
5747 	 * physical geometry (geom_cache) to values that will fit
5748 	 * in a dk_geom structure.
5749 	 */
5750 	if (ISCD(un)) {
5751 		phys_spc = un->un_pgeom.g_nhead * un->un_pgeom.g_nsect;
5752 	} else {
5753 		/* Convert physical geometry to disk geometry */
5754 		bzero(&un_g, sizeof (struct dk_geom));
5755 		sd_convert_geometry(un->un_blockcount, &un_g);
5756 		bcopy(&un_g, &un->un_g, sizeof (un->un_g));
5757 		phys_spc = un->un_g.dkg_nhead * un->un_g.dkg_nsect;
5758 	}
5759 
5760 	ASSERT(phys_spc != 0);
5761 	un->un_g.dkg_pcyl = un->un_solaris_size / phys_spc;
5762 	un->un_g.dkg_acyl = DK_ACYL;
5763 	un->un_g.dkg_ncyl = un->un_g.dkg_pcyl - DK_ACYL;
5764 	disksize = un->un_g.dkg_ncyl * phys_spc;
5765 
5766 	if (ISCD(un)) {
5767 		/*
5768 		 * CD's don't use the "heads * sectors * cyls"-type of
5769 		 * geometry, but instead use the entire capacity of the media.
5770 		 */
5771 		disksize = un->un_solaris_size;
5772 		un->un_g.dkg_nhead = 1;
5773 		un->un_g.dkg_nsect = 1;
5774 		un->un_g.dkg_rpm =
5775 		    (un->un_pgeom.g_rpm == 0) ? 200 : un->un_pgeom.g_rpm;
5776 
5777 		un->un_vtoc.v_part[0].p_start = 0;
5778 		un->un_vtoc.v_part[0].p_size  = disksize;
5779 		un->un_vtoc.v_part[0].p_tag   = V_BACKUP;
5780 		un->un_vtoc.v_part[0].p_flag  = V_UNMNT;
5781 
5782 		un->un_map[0].dkl_cylno = 0;
5783 		un->un_map[0].dkl_nblk  = disksize;
5784 		un->un_offset[0] = 0;
5785 
5786 	} else {
5787 		/*
5788 		 * Hard disks and removable media cartridges
5789 		 */
5790 		un->un_g.dkg_rpm =
5791 		    (un->un_pgeom.g_rpm == 0) ? 3600: un->un_pgeom.g_rpm;
5792 		un->un_vtoc.v_sectorsz = un->un_sys_blocksize;
5793 
5794 		/* Add boot slice */
5795 		un->un_vtoc.v_part[8].p_start = 0;
5796 		un->un_vtoc.v_part[8].p_size  = phys_spc;
5797 		un->un_vtoc.v_part[8].p_tag   = V_BOOT;
5798 		un->un_vtoc.v_part[8].p_flag  = V_UNMNT;
5799 
5800 		un->un_map[8].dkl_cylno = 0;
5801 		un->un_map[8].dkl_nblk  = phys_spc;
5802 		un->un_offset[8] = 0;
5803 	}
5804 
5805 	un->un_g.dkg_apc = 0;
5806 	un->un_vtoc.v_nparts = V_NUMPAR;
5807 
5808 	/* Add backup slice */
5809 	un->un_vtoc.v_part[2].p_start = 0;
5810 	un->un_vtoc.v_part[2].p_size  = disksize;
5811 	un->un_vtoc.v_part[2].p_tag   = V_BACKUP;
5812 	un->un_vtoc.v_part[2].p_flag  = V_UNMNT;
5813 
5814 	un->un_map[2].dkl_cylno = 0;
5815 	un->un_map[2].dkl_nblk  = disksize;
5816 	un->un_offset[2] = 0;
5817 
5818 	(void) sprintf(un->un_vtoc.v_asciilabel, "DEFAULT cyl %d alt %d"
5819 	    " hd %d sec %d", un->un_g.dkg_ncyl, un->un_g.dkg_acyl,
5820 	    un->un_g.dkg_nhead, un->un_g.dkg_nsect);
5821 
5822 #else
5823 #error "No VTOC format defined."
5824 #endif
5825 
5826 	un->un_g.dkg_read_reinstruct  = 0;
5827 	un->un_g.dkg_write_reinstruct = 0;
5828 
5829 	un->un_g.dkg_intrlv = 1;
5830 
5831 	un->un_vtoc.v_version = V_VERSION;
5832 	un->un_vtoc.v_sanity  = VTOC_SANE;
5833 
5834 	un->un_f_geometry_is_valid = TRUE;
5835 
5836 	SD_INFO(SD_LOG_COMMON, un,
5837 	    "sd_build_default_label: Default label created: "
5838 	    "cyl: %d\tacyl: %d\tnhead: %d\tnsect: %d\tcap: %d\n",
5839 	    un->un_g.dkg_ncyl, un->un_g.dkg_acyl, un->un_g.dkg_nhead,
5840 	    un->un_g.dkg_nsect, un->un_blockcount);
5841 }
5842 
5843 
5844 #if defined(_FIRMWARE_NEEDS_FDISK)
5845 /*
5846  * Max CHS values, as they are encoded into bytes, for 1022/254/63
5847  */
5848 #define	LBA_MAX_SECT	(63 | ((1022 & 0x300) >> 2))
5849 #define	LBA_MAX_CYL	(1022 & 0xFF)
5850 #define	LBA_MAX_HEAD	(254)
5851 
5852 
5853 /*
5854  *    Function: sd_has_max_chs_vals
5855  *
5856  * Description: Return TRUE if Cylinder-Head-Sector values are all at maximum.
5857  *
5858  *   Arguments: fdp - ptr to CHS info
5859  *
5860  * Return Code: True or false
5861  *
5862  *     Context: Any.
5863  */
5864 
5865 static int
5866 sd_has_max_chs_vals(struct ipart *fdp)
5867 {
5868 	return ((fdp->begcyl  == LBA_MAX_CYL)	&&
5869 	    (fdp->beghead == LBA_MAX_HEAD)	&&
5870 	    (fdp->begsect == LBA_MAX_SECT)	&&
5871 	    (fdp->endcyl  == LBA_MAX_CYL)	&&
5872 	    (fdp->endhead == LBA_MAX_HEAD)	&&
5873 	    (fdp->endsect == LBA_MAX_SECT));
5874 }
5875 #endif
5876 
5877 
5878 /*
5879  *    Function: sd_inq_fill
5880  *
5881  * Description: Print a piece of inquiry data, cleaned up for non-printable
5882  *		characters and stopping at the first space character after
5883  *		the beginning of the passed string;
5884  *
5885  *   Arguments: p - source string
5886  *		l - maximum length to copy
5887  *		s - destination string
5888  *
5889  *     Context: Any.
5890  */
5891 
5892 static void
5893 sd_inq_fill(char *p, int l, char *s)
5894 {
5895 	unsigned i = 0;
5896 	char c;
5897 
5898 	while (i++ < l) {
5899 		if ((c = *p++) < ' ' || c >= 0x7F) {
5900 			c = '*';
5901 		} else if (i != 1 && c == ' ') {
5902 			break;
5903 		}
5904 		*s++ = c;
5905 	}
5906 	*s++ = 0;
5907 }
5908 
5909 
5910 /*
5911  *    Function: sd_register_devid
5912  *
5913  * Description: This routine will obtain the device id information from the
5914  *		target, obtain the serial number, and register the device
5915  *		id with the ddi framework.
5916  *
5917  *   Arguments: devi - the system's dev_info_t for the device.
5918  *		un - driver soft state (unit) structure
5919  *		reservation_flag - indicates if a reservation conflict
5920  *		occurred during attach
5921  *
5922  *     Context: Kernel Thread
5923  */
5924 static void
5925 sd_register_devid(struct sd_lun *un, dev_info_t *devi, int reservation_flag)
5926 {
5927 	int		rval		= 0;
5928 	uchar_t		*inq80		= NULL;
5929 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5930 	size_t		inq80_resid	= 0;
5931 	uchar_t		*inq83		= NULL;
5932 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5933 	size_t		inq83_resid	= 0;
5934 
5935 	ASSERT(un != NULL);
5936 	ASSERT(mutex_owned(SD_MUTEX(un)));
5937 	ASSERT((SD_DEVINFO(un)) == devi);
5938 
5939 	/*
5940 	 * This is the case of antiquated Sun disk drives that have the
5941 	 * FAB_DEVID property set in the disk_table.  These drives
5942 	 * manage the devid's by storing them in last 2 available sectors
5943 	 * on the drive and have them fabricated by the ddi layer by calling
5944 	 * ddi_devid_init and passing the DEVID_FAB flag.
5945 	 */
5946 	if (un->un_f_opt_fab_devid == TRUE) {
5947 		/*
5948 		 * Depending on EINVAL isn't reliable, since a reserved disk
5949 		 * may result in invalid geometry, so check to make sure a
5950 		 * reservation conflict did not occur during attach.
5951 		 */
5952 		if ((sd_get_devid(un) == EINVAL) &&
5953 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5954 			/*
5955 			 * The devid is invalid AND there is no reservation
5956 			 * conflict.  Fabricate a new devid.
5957 			 */
5958 			(void) sd_create_devid(un);
5959 		}
5960 
5961 		/* Register the devid if it exists */
5962 		if (un->un_devid != NULL) {
5963 			(void) ddi_devid_register(SD_DEVINFO(un),
5964 			    un->un_devid);
5965 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5966 			    "sd_register_devid: Devid Fabricated\n");
5967 		}
5968 		return;
5969 	}
5970 
5971 	/*
5972 	 * We check the availibility of the World Wide Name (0x83) and Unit
5973 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5974 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5975 	 * 0x83 is availible, that is the best choice.  Our next choice is
5976 	 * 0x80.  If neither are availible, we munge the devid from the device
5977 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5978 	 * to fabricate a devid for non-Sun qualified disks.
5979 	 */
5980 	if (sd_check_vpd_page_support(un) == 0) {
5981 		/* collect page 80 data if available */
5982 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5983 
5984 			mutex_exit(SD_MUTEX(un));
5985 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5986 			rval = sd_send_scsi_INQUIRY(un, inq80, inq80_len,
5987 			    0x01, 0x80, &inq80_resid);
5988 
5989 			if (rval != 0) {
5990 				kmem_free(inq80, inq80_len);
5991 				inq80 = NULL;
5992 				inq80_len = 0;
5993 			}
5994 			mutex_enter(SD_MUTEX(un));
5995 		}
5996 
5997 		/* collect page 83 data if available */
5998 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5999 			mutex_exit(SD_MUTEX(un));
6000 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
6001 			rval = sd_send_scsi_INQUIRY(un, inq83, inq83_len,
6002 			    0x01, 0x83, &inq83_resid);
6003 
6004 			if (rval != 0) {
6005 				kmem_free(inq83, inq83_len);
6006 				inq83 = NULL;
6007 				inq83_len = 0;
6008 			}
6009 			mutex_enter(SD_MUTEX(un));
6010 		}
6011 	}
6012 
6013 	/* encode best devid possible based on data available */
6014 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
6015 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
6016 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
6017 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
6018 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
6019 
6020 		/* devid successfully encoded, register devid */
6021 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
6022 
6023 	} else {
6024 		/*
6025 		 * Unable to encode a devid based on data available.
6026 		 * This is not a Sun qualified disk.  Older Sun disk
6027 		 * drives that have the SD_FAB_DEVID property
6028 		 * set in the disk_table and non Sun qualified
6029 		 * disks are treated in the same manner.  These
6030 		 * drives manage the devid's by storing them in
6031 		 * last 2 available sectors on the drive and
6032 		 * have them fabricated by the ddi layer by
6033 		 * calling ddi_devid_init and passing the
6034 		 * DEVID_FAB flag.
6035 		 * Create a fabricate devid only if there's no
6036 		 * fabricate devid existed.
6037 		 */
6038 		if (sd_get_devid(un) == EINVAL) {
6039 			(void) sd_create_devid(un);
6040 			un->un_f_opt_fab_devid = TRUE;
6041 		}
6042 
6043 		/* Register the devid if it exists */
6044 		if (un->un_devid != NULL) {
6045 			(void) ddi_devid_register(SD_DEVINFO(un),
6046 			    un->un_devid);
6047 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6048 			    "sd_register_devid: devid fabricated using "
6049 			    "ddi framework\n");
6050 		}
6051 	}
6052 
6053 	/* clean up resources */
6054 	if (inq80 != NULL) {
6055 		kmem_free(inq80, inq80_len);
6056 	}
6057 	if (inq83 != NULL) {
6058 		kmem_free(inq83, inq83_len);
6059 	}
6060 }
6061 
6062 static daddr_t
6063 sd_get_devid_block(struct sd_lun *un)
6064 {
6065 	daddr_t			spc, blk, head, cyl;
6066 
6067 	if (un->un_blockcount <= DK_MAX_BLOCKS) {
6068 		/* this geometry doesn't allow us to write a devid */
6069 		if (un->un_g.dkg_acyl < 2) {
6070 			return (-1);
6071 		}
6072 
6073 		/*
6074 		 * Subtract 2 guarantees that the next to last cylinder
6075 		 * is used
6076 		 */
6077 		cyl  = un->un_g.dkg_ncyl  + un->un_g.dkg_acyl - 2;
6078 		spc  = un->un_g.dkg_nhead * un->un_g.dkg_nsect;
6079 		head = un->un_g.dkg_nhead - 1;
6080 		blk  = (cyl * (spc - un->un_g.dkg_apc)) +
6081 		    (head * un->un_g.dkg_nsect) + 1;
6082 	} else {
6083 		if (un->un_reserved != -1) {
6084 			blk = un->un_map[un->un_reserved].dkl_cylno + 1;
6085 		} else {
6086 			return (-1);
6087 		}
6088 	}
6089 	return (blk);
6090 }
6091 
6092 /*
6093  *    Function: sd_get_devid
6094  *
6095  * Description: This routine will return 0 if a valid device id has been
6096  *		obtained from the target and stored in the soft state. If a
6097  *		valid device id has not been previously read and stored, a
6098  *		read attempt will be made.
6099  *
6100  *   Arguments: un - driver soft state (unit) structure
6101  *
6102  * Return Code: 0 if we successfully get the device id
6103  *
6104  *     Context: Kernel Thread
6105  */
6106 
6107 static int
6108 sd_get_devid(struct sd_lun *un)
6109 {
6110 	struct dk_devid		*dkdevid;
6111 	ddi_devid_t		tmpid;
6112 	uint_t			*ip;
6113 	size_t			sz;
6114 	daddr_t			blk;
6115 	int			status;
6116 	int			chksum;
6117 	int			i;
6118 	size_t			buffer_size;
6119 
6120 	ASSERT(un != NULL);
6121 	ASSERT(mutex_owned(SD_MUTEX(un)));
6122 
6123 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
6124 	    un);
6125 
6126 	if (un->un_devid != NULL) {
6127 		return (0);
6128 	}
6129 
6130 	blk = sd_get_devid_block(un);
6131 	if (blk < 0)
6132 		return (EINVAL);
6133 
6134 	/*
6135 	 * Read and verify device id, stored in the reserved cylinders at the
6136 	 * end of the disk. Backup label is on the odd sectors of the last
6137 	 * track of the last cylinder. Device id will be on track of the next
6138 	 * to last cylinder.
6139 	 */
6140 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
6141 	mutex_exit(SD_MUTEX(un));
6142 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
6143 	status = sd_send_scsi_READ(un, dkdevid, buffer_size, blk,
6144 	    SD_PATH_DIRECT);
6145 	if (status != 0) {
6146 		goto error;
6147 	}
6148 
6149 	/* Validate the revision */
6150 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
6151 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
6152 		status = EINVAL;
6153 		goto error;
6154 	}
6155 
6156 	/* Calculate the checksum */
6157 	chksum = 0;
6158 	ip = (uint_t *)dkdevid;
6159 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
6160 	    i++) {
6161 		chksum ^= ip[i];
6162 	}
6163 
6164 	/* Compare the checksums */
6165 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
6166 		status = EINVAL;
6167 		goto error;
6168 	}
6169 
6170 	/* Validate the device id */
6171 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
6172 		status = EINVAL;
6173 		goto error;
6174 	}
6175 
6176 	/*
6177 	 * Store the device id in the driver soft state
6178 	 */
6179 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
6180 	tmpid = kmem_alloc(sz, KM_SLEEP);
6181 
6182 	mutex_enter(SD_MUTEX(un));
6183 
6184 	un->un_devid = tmpid;
6185 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
6186 
6187 	kmem_free(dkdevid, buffer_size);
6188 
6189 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
6190 
6191 	return (status);
6192 error:
6193 	mutex_enter(SD_MUTEX(un));
6194 	kmem_free(dkdevid, buffer_size);
6195 	return (status);
6196 }
6197 
6198 
6199 /*
6200  *    Function: sd_create_devid
6201  *
6202  * Description: This routine will fabricate the device id and write it
6203  *		to the disk.
6204  *
6205  *   Arguments: un - driver soft state (unit) structure
6206  *
6207  * Return Code: value of the fabricated device id
6208  *
6209  *     Context: Kernel Thread
6210  */
6211 
6212 static ddi_devid_t
6213 sd_create_devid(struct sd_lun *un)
6214 {
6215 	ASSERT(un != NULL);
6216 
6217 	/* Fabricate the devid */
6218 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
6219 	    == DDI_FAILURE) {
6220 		return (NULL);
6221 	}
6222 
6223 	/* Write the devid to disk */
6224 	if (sd_write_deviceid(un) != 0) {
6225 		ddi_devid_free(un->un_devid);
6226 		un->un_devid = NULL;
6227 	}
6228 
6229 	return (un->un_devid);
6230 }
6231 
6232 
6233 /*
6234  *    Function: sd_write_deviceid
6235  *
6236  * Description: This routine will write the device id to the disk
6237  *		reserved sector.
6238  *
6239  *   Arguments: un - driver soft state (unit) structure
6240  *
6241  * Return Code: EINVAL
6242  *		value returned by sd_send_scsi_cmd
6243  *
6244  *     Context: Kernel Thread
6245  */
6246 
6247 static int
6248 sd_write_deviceid(struct sd_lun *un)
6249 {
6250 	struct dk_devid		*dkdevid;
6251 	daddr_t			blk;
6252 	uint_t			*ip, chksum;
6253 	int			status;
6254 	int			i;
6255 
6256 	ASSERT(mutex_owned(SD_MUTEX(un)));
6257 
6258 	blk = sd_get_devid_block(un);
6259 	if (blk < 0)
6260 		return (-1);
6261 	mutex_exit(SD_MUTEX(un));
6262 
6263 	/* Allocate the buffer */
6264 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
6265 
6266 	/* Fill in the revision */
6267 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
6268 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
6269 
6270 	/* Copy in the device id */
6271 	mutex_enter(SD_MUTEX(un));
6272 	bcopy(un->un_devid, &dkdevid->dkd_devid,
6273 	    ddi_devid_sizeof(un->un_devid));
6274 	mutex_exit(SD_MUTEX(un));
6275 
6276 	/* Calculate the checksum */
6277 	chksum = 0;
6278 	ip = (uint_t *)dkdevid;
6279 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
6280 	    i++) {
6281 		chksum ^= ip[i];
6282 	}
6283 
6284 	/* Fill-in checksum */
6285 	DKD_FORMCHKSUM(chksum, dkdevid);
6286 
6287 	/* Write the reserved sector */
6288 	status = sd_send_scsi_WRITE(un, dkdevid, un->un_sys_blocksize, blk,
6289 	    SD_PATH_DIRECT);
6290 
6291 	kmem_free(dkdevid, un->un_sys_blocksize);
6292 
6293 	mutex_enter(SD_MUTEX(un));
6294 	return (status);
6295 }
6296 
6297 
6298 /*
6299  *    Function: sd_check_vpd_page_support
6300  *
6301  * Description: This routine sends an inquiry command with the EVPD bit set and
6302  *		a page code of 0x00 to the device. It is used to determine which
6303  *		vital product pages are availible to find the devid. We are
6304  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
6305  *		device does not support that command.
6306  *
6307  *   Arguments: un  - driver soft state (unit) structure
6308  *
6309  * Return Code: 0 - success
6310  *		1 - check condition
6311  *
6312  *     Context: This routine can sleep.
6313  */
6314 
6315 static int
6316 sd_check_vpd_page_support(struct sd_lun *un)
6317 {
6318 	uchar_t	*page_list	= NULL;
6319 	uchar_t	page_length	= 0xff;	/* Use max possible length */
6320 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
6321 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
6322 	int    	rval		= 0;
6323 	int	counter;
6324 
6325 	ASSERT(un != NULL);
6326 	ASSERT(mutex_owned(SD_MUTEX(un)));
6327 
6328 	mutex_exit(SD_MUTEX(un));
6329 
6330 	/*
6331 	 * We'll set the page length to the maximum to save figuring it out
6332 	 * with an additional call.
6333 	 */
6334 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
6335 
6336 	rval = sd_send_scsi_INQUIRY(un, page_list, page_length, evpd,
6337 	    page_code, NULL);
6338 
6339 	mutex_enter(SD_MUTEX(un));
6340 
6341 	/*
6342 	 * Now we must validate that the device accepted the command, as some
6343 	 * drives do not support it.  If the drive does support it, we will
6344 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
6345 	 * not, we return -1.
6346 	 */
6347 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
6348 		/* Loop to find one of the 2 pages we need */
6349 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
6350 
6351 		/*
6352 		 * Pages are returned in ascending order, and 0x83 is what we
6353 		 * are hoping for.
6354 		 */
6355 		while ((page_list[counter] <= 0x83) &&
6356 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
6357 		    VPD_HEAD_OFFSET))) {
6358 			/*
6359 			 * Add 3 because page_list[3] is the number of
6360 			 * pages minus 3
6361 			 */
6362 
6363 			switch (page_list[counter]) {
6364 			case 0x00:
6365 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
6366 				break;
6367 			case 0x80:
6368 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
6369 				break;
6370 			case 0x81:
6371 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
6372 				break;
6373 			case 0x82:
6374 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
6375 				break;
6376 			case 0x83:
6377 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
6378 				break;
6379 			}
6380 			counter++;
6381 		}
6382 
6383 	} else {
6384 		rval = -1;
6385 
6386 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6387 		    "sd_check_vpd_page_support: This drive does not implement "
6388 		    "VPD pages.\n");
6389 	}
6390 
6391 	kmem_free(page_list, page_length);
6392 
6393 	return (rval);
6394 }
6395 
6396 
6397 /*
6398  *    Function: sd_setup_pm
6399  *
6400  * Description: Initialize Power Management on the device
6401  *
6402  *     Context: Kernel Thread
6403  */
6404 
6405 static void
6406 sd_setup_pm(struct sd_lun *un, dev_info_t *devi)
6407 {
6408 	uint_t	log_page_size;
6409 	uchar_t	*log_page_data;
6410 	int	rval;
6411 
6412 	/*
6413 	 * Since we are called from attach, holding a mutex for
6414 	 * un is unnecessary. Because some of the routines called
6415 	 * from here require SD_MUTEX to not be held, assert this
6416 	 * right up front.
6417 	 */
6418 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6419 	/*
6420 	 * Since the sd device does not have the 'reg' property,
6421 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
6422 	 * The following code is to tell cpr that this device
6423 	 * DOES need to be suspended and resumed.
6424 	 */
6425 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
6426 	    "pm-hardware-state", "needs-suspend-resume");
6427 
6428 	/*
6429 	 * This complies with the new power management framework
6430 	 * for certain desktop machines. Create the pm_components
6431 	 * property as a string array property.
6432 	 */
6433 	if (un->un_f_pm_supported) {
6434 		/*
6435 		 * not all devices have a motor, try it first.
6436 		 * some devices may return ILLEGAL REQUEST, some
6437 		 * will hang
6438 		 * The following START_STOP_UNIT is used to check if target
6439 		 * device has a motor.
6440 		 */
6441 		un->un_f_start_stop_supported = TRUE;
6442 		if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
6443 		    SD_PATH_DIRECT) != 0) {
6444 			un->un_f_start_stop_supported = FALSE;
6445 		}
6446 
6447 		/*
6448 		 * create pm properties anyways otherwise the parent can't
6449 		 * go to sleep
6450 		 */
6451 		(void) sd_create_pm_components(devi, un);
6452 		un->un_f_pm_is_enabled = TRUE;
6453 		return;
6454 	}
6455 
6456 	if (!un->un_f_log_sense_supported) {
6457 		un->un_power_level = SD_SPINDLE_ON;
6458 		un->un_f_pm_is_enabled = FALSE;
6459 		return;
6460 	}
6461 
6462 	rval = sd_log_page_supported(un, START_STOP_CYCLE_PAGE);
6463 
6464 #ifdef	SDDEBUG
6465 	if (sd_force_pm_supported) {
6466 		/* Force a successful result */
6467 		rval = 1;
6468 	}
6469 #endif
6470 
6471 	/*
6472 	 * If the start-stop cycle counter log page is not supported
6473 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
6474 	 * then we should not create the pm_components property.
6475 	 */
6476 	if (rval == -1) {
6477 		/*
6478 		 * Error.
6479 		 * Reading log sense failed, most likely this is
6480 		 * an older drive that does not support log sense.
6481 		 * If this fails auto-pm is not supported.
6482 		 */
6483 		un->un_power_level = SD_SPINDLE_ON;
6484 		un->un_f_pm_is_enabled = FALSE;
6485 
6486 	} else if (rval == 0) {
6487 		/*
6488 		 * Page not found.
6489 		 * The start stop cycle counter is implemented as page
6490 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
6491 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
6492 		 */
6493 		if (sd_log_page_supported(un, START_STOP_CYCLE_VU_PAGE) == 1) {
6494 			/*
6495 			 * Page found, use this one.
6496 			 */
6497 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
6498 			un->un_f_pm_is_enabled = TRUE;
6499 		} else {
6500 			/*
6501 			 * Error or page not found.
6502 			 * auto-pm is not supported for this device.
6503 			 */
6504 			un->un_power_level = SD_SPINDLE_ON;
6505 			un->un_f_pm_is_enabled = FALSE;
6506 		}
6507 	} else {
6508 		/*
6509 		 * Page found, use it.
6510 		 */
6511 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
6512 		un->un_f_pm_is_enabled = TRUE;
6513 	}
6514 
6515 
6516 	if (un->un_f_pm_is_enabled == TRUE) {
6517 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6518 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6519 
6520 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
6521 		    log_page_size, un->un_start_stop_cycle_page,
6522 		    0x01, 0, SD_PATH_DIRECT);
6523 #ifdef	SDDEBUG
6524 		if (sd_force_pm_supported) {
6525 			/* Force a successful result */
6526 			rval = 0;
6527 		}
6528 #endif
6529 
6530 		/*
6531 		 * If the Log sense for Page( Start/stop cycle counter page)
6532 		 * succeeds, then power managment is supported and we can
6533 		 * enable auto-pm.
6534 		 */
6535 		if (rval == 0)  {
6536 			(void) sd_create_pm_components(devi, un);
6537 		} else {
6538 			un->un_power_level = SD_SPINDLE_ON;
6539 			un->un_f_pm_is_enabled = FALSE;
6540 		}
6541 
6542 		kmem_free(log_page_data, log_page_size);
6543 	}
6544 }
6545 
6546 
6547 /*
6548  *    Function: sd_create_pm_components
6549  *
6550  * Description: Initialize PM property.
6551  *
6552  *     Context: Kernel thread context
6553  */
6554 
6555 static void
6556 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
6557 {
6558 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
6559 
6560 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6561 
6562 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6563 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
6564 		/*
6565 		 * When components are initially created they are idle,
6566 		 * power up any non-removables.
6567 		 * Note: the return value of pm_raise_power can't be used
6568 		 * for determining if PM should be enabled for this device.
6569 		 * Even if you check the return values and remove this
6570 		 * property created above, the PM framework will not honor the
6571 		 * change after the first call to pm_raise_power. Hence,
6572 		 * removal of that property does not help if pm_raise_power
6573 		 * fails. In the case of removable media, the start/stop
6574 		 * will fail if the media is not present.
6575 		 */
6576 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6577 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
6578 			mutex_enter(SD_MUTEX(un));
6579 			un->un_power_level = SD_SPINDLE_ON;
6580 			mutex_enter(&un->un_pm_mutex);
6581 			/* Set to on and not busy. */
6582 			un->un_pm_count = 0;
6583 		} else {
6584 			mutex_enter(SD_MUTEX(un));
6585 			un->un_power_level = SD_SPINDLE_OFF;
6586 			mutex_enter(&un->un_pm_mutex);
6587 			/* Set to off. */
6588 			un->un_pm_count = -1;
6589 		}
6590 		mutex_exit(&un->un_pm_mutex);
6591 		mutex_exit(SD_MUTEX(un));
6592 	} else {
6593 		un->un_power_level = SD_SPINDLE_ON;
6594 		un->un_f_pm_is_enabled = FALSE;
6595 	}
6596 }
6597 
6598 
6599 /*
6600  *    Function: sd_ddi_suspend
6601  *
6602  * Description: Performs system power-down operations. This includes
6603  *		setting the drive state to indicate its suspended so
6604  *		that no new commands will be accepted. Also, wait for
6605  *		all commands that are in transport or queued to a timer
6606  *		for retry to complete. All timeout threads are cancelled.
6607  *
6608  * Return Code: DDI_FAILURE or DDI_SUCCESS
6609  *
6610  *     Context: Kernel thread context
6611  */
6612 
6613 static int
6614 sd_ddi_suspend(dev_info_t *devi)
6615 {
6616 	struct	sd_lun	*un;
6617 	clock_t		wait_cmds_complete;
6618 
6619 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6620 	if (un == NULL) {
6621 		return (DDI_FAILURE);
6622 	}
6623 
6624 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6625 
6626 	mutex_enter(SD_MUTEX(un));
6627 
6628 	/* Return success if the device is already suspended. */
6629 	if (un->un_state == SD_STATE_SUSPENDED) {
6630 		mutex_exit(SD_MUTEX(un));
6631 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6632 		    "device already suspended, exiting\n");
6633 		return (DDI_SUCCESS);
6634 	}
6635 
6636 	/* Return failure if the device is being used by HA */
6637 	if (un->un_resvd_status &
6638 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6639 		mutex_exit(SD_MUTEX(un));
6640 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6641 		    "device in use by HA, exiting\n");
6642 		return (DDI_FAILURE);
6643 	}
6644 
6645 	/*
6646 	 * Return failure if the device is in a resource wait
6647 	 * or power changing state.
6648 	 */
6649 	if ((un->un_state == SD_STATE_RWAIT) ||
6650 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6651 		mutex_exit(SD_MUTEX(un));
6652 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6653 		    "device in resource wait state, exiting\n");
6654 		return (DDI_FAILURE);
6655 	}
6656 
6657 
6658 	un->un_save_state = un->un_last_state;
6659 	New_state(un, SD_STATE_SUSPENDED);
6660 
6661 	/*
6662 	 * Wait for all commands that are in transport or queued to a timer
6663 	 * for retry to complete.
6664 	 *
6665 	 * While waiting, no new commands will be accepted or sent because of
6666 	 * the new state we set above.
6667 	 *
6668 	 * Wait till current operation has completed. If we are in the resource
6669 	 * wait state (with an intr outstanding) then we need to wait till the
6670 	 * intr completes and starts the next cmd. We want to wait for
6671 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6672 	 */
6673 	wait_cmds_complete = ddi_get_lbolt() +
6674 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6675 
6676 	while (un->un_ncmds_in_transport != 0) {
6677 		/*
6678 		 * Fail if commands do not finish in the specified time.
6679 		 */
6680 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6681 		    wait_cmds_complete) == -1) {
6682 			/*
6683 			 * Undo the state changes made above. Everything
6684 			 * must go back to it's original value.
6685 			 */
6686 			Restore_state(un);
6687 			un->un_last_state = un->un_save_state;
6688 			/* Wake up any threads that might be waiting. */
6689 			cv_broadcast(&un->un_suspend_cv);
6690 			mutex_exit(SD_MUTEX(un));
6691 			SD_ERROR(SD_LOG_IO_PM, un,
6692 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6693 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6694 			return (DDI_FAILURE);
6695 		}
6696 	}
6697 
6698 	/*
6699 	 * Cancel SCSI watch thread and timeouts, if any are active
6700 	 */
6701 
6702 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6703 		opaque_t temp_token = un->un_swr_token;
6704 		mutex_exit(SD_MUTEX(un));
6705 		scsi_watch_suspend(temp_token);
6706 		mutex_enter(SD_MUTEX(un));
6707 	}
6708 
6709 	if (un->un_reset_throttle_timeid != NULL) {
6710 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6711 		un->un_reset_throttle_timeid = NULL;
6712 		mutex_exit(SD_MUTEX(un));
6713 		(void) untimeout(temp_id);
6714 		mutex_enter(SD_MUTEX(un));
6715 	}
6716 
6717 	if (un->un_dcvb_timeid != NULL) {
6718 		timeout_id_t temp_id = un->un_dcvb_timeid;
6719 		un->un_dcvb_timeid = NULL;
6720 		mutex_exit(SD_MUTEX(un));
6721 		(void) untimeout(temp_id);
6722 		mutex_enter(SD_MUTEX(un));
6723 	}
6724 
6725 	mutex_enter(&un->un_pm_mutex);
6726 	if (un->un_pm_timeid != NULL) {
6727 		timeout_id_t temp_id = un->un_pm_timeid;
6728 		un->un_pm_timeid = NULL;
6729 		mutex_exit(&un->un_pm_mutex);
6730 		mutex_exit(SD_MUTEX(un));
6731 		(void) untimeout(temp_id);
6732 		mutex_enter(SD_MUTEX(un));
6733 	} else {
6734 		mutex_exit(&un->un_pm_mutex);
6735 	}
6736 
6737 	if (un->un_retry_timeid != NULL) {
6738 		timeout_id_t temp_id = un->un_retry_timeid;
6739 		un->un_retry_timeid = NULL;
6740 		mutex_exit(SD_MUTEX(un));
6741 		(void) untimeout(temp_id);
6742 		mutex_enter(SD_MUTEX(un));
6743 	}
6744 
6745 	if (un->un_direct_priority_timeid != NULL) {
6746 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6747 		un->un_direct_priority_timeid = NULL;
6748 		mutex_exit(SD_MUTEX(un));
6749 		(void) untimeout(temp_id);
6750 		mutex_enter(SD_MUTEX(un));
6751 	}
6752 
6753 	if (un->un_f_is_fibre == TRUE) {
6754 		/*
6755 		 * Remove callbacks for insert and remove events
6756 		 */
6757 		if (un->un_insert_event != NULL) {
6758 			mutex_exit(SD_MUTEX(un));
6759 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6760 			mutex_enter(SD_MUTEX(un));
6761 			un->un_insert_event = NULL;
6762 		}
6763 
6764 		if (un->un_remove_event != NULL) {
6765 			mutex_exit(SD_MUTEX(un));
6766 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6767 			mutex_enter(SD_MUTEX(un));
6768 			un->un_remove_event = NULL;
6769 		}
6770 	}
6771 
6772 	mutex_exit(SD_MUTEX(un));
6773 
6774 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6775 
6776 	return (DDI_SUCCESS);
6777 }
6778 
6779 
6780 /*
6781  *    Function: sd_ddi_pm_suspend
6782  *
6783  * Description: Set the drive state to low power.
6784  *		Someone else is required to actually change the drive
6785  *		power level.
6786  *
6787  *   Arguments: un - driver soft state (unit) structure
6788  *
6789  * Return Code: DDI_FAILURE or DDI_SUCCESS
6790  *
6791  *     Context: Kernel thread context
6792  */
6793 
6794 static int
6795 sd_ddi_pm_suspend(struct sd_lun *un)
6796 {
6797 	ASSERT(un != NULL);
6798 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
6799 
6800 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6801 	mutex_enter(SD_MUTEX(un));
6802 
6803 	/*
6804 	 * Exit if power management is not enabled for this device, or if
6805 	 * the device is being used by HA.
6806 	 */
6807 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6808 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6809 		mutex_exit(SD_MUTEX(un));
6810 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
6811 		return (DDI_SUCCESS);
6812 	}
6813 
6814 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
6815 	    un->un_ncmds_in_driver);
6816 
6817 	/*
6818 	 * See if the device is not busy, ie.:
6819 	 *    - we have no commands in the driver for this device
6820 	 *    - not waiting for resources
6821 	 */
6822 	if ((un->un_ncmds_in_driver == 0) &&
6823 	    (un->un_state != SD_STATE_RWAIT)) {
6824 		/*
6825 		 * The device is not busy, so it is OK to go to low power state.
6826 		 * Indicate low power, but rely on someone else to actually
6827 		 * change it.
6828 		 */
6829 		mutex_enter(&un->un_pm_mutex);
6830 		un->un_pm_count = -1;
6831 		mutex_exit(&un->un_pm_mutex);
6832 		un->un_power_level = SD_SPINDLE_OFF;
6833 	}
6834 
6835 	mutex_exit(SD_MUTEX(un));
6836 
6837 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
6838 
6839 	return (DDI_SUCCESS);
6840 }
6841 
6842 
6843 /*
6844  *    Function: sd_ddi_resume
6845  *
6846  * Description: Performs system power-up operations..
6847  *
6848  * Return Code: DDI_SUCCESS
6849  *		DDI_FAILURE
6850  *
6851  *     Context: Kernel thread context
6852  */
6853 
6854 static int
6855 sd_ddi_resume(dev_info_t *devi)
6856 {
6857 	struct	sd_lun	*un;
6858 
6859 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6860 	if (un == NULL) {
6861 		return (DDI_FAILURE);
6862 	}
6863 
6864 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6865 
6866 	mutex_enter(SD_MUTEX(un));
6867 	Restore_state(un);
6868 
6869 	/*
6870 	 * Restore the state which was saved to give the
6871 	 * the right state in un_last_state
6872 	 */
6873 	un->un_last_state = un->un_save_state;
6874 	/*
6875 	 * Note: throttle comes back at full.
6876 	 * Also note: this MUST be done before calling pm_raise_power
6877 	 * otherwise the system can get hung in biowait. The scenario where
6878 	 * this'll happen is under cpr suspend. Writing of the system
6879 	 * state goes through sddump, which writes 0 to un_throttle. If
6880 	 * writing the system state then fails, example if the partition is
6881 	 * too small, then cpr attempts a resume. If throttle isn't restored
6882 	 * from the saved value until after calling pm_raise_power then
6883 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6884 	 * in biowait.
6885 	 */
6886 	un->un_throttle = un->un_saved_throttle;
6887 
6888 	/*
6889 	 * The chance of failure is very rare as the only command done in power
6890 	 * entry point is START command when you transition from 0->1 or
6891 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6892 	 * which suspend was done. Ignore the return value as the resume should
6893 	 * not be failed. In the case of removable media the media need not be
6894 	 * inserted and hence there is a chance that raise power will fail with
6895 	 * media not present.
6896 	 */
6897 	if (un->un_f_attach_spinup) {
6898 		mutex_exit(SD_MUTEX(un));
6899 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
6900 		mutex_enter(SD_MUTEX(un));
6901 	}
6902 
6903 	/*
6904 	 * Don't broadcast to the suspend cv and therefore possibly
6905 	 * start I/O until after power has been restored.
6906 	 */
6907 	cv_broadcast(&un->un_suspend_cv);
6908 	cv_broadcast(&un->un_state_cv);
6909 
6910 	/* restart thread */
6911 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6912 		scsi_watch_resume(un->un_swr_token);
6913 	}
6914 
6915 #if (defined(__fibre))
6916 	if (un->un_f_is_fibre == TRUE) {
6917 		/*
6918 		 * Add callbacks for insert and remove events
6919 		 */
6920 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6921 			sd_init_event_callbacks(un);
6922 		}
6923 	}
6924 #endif
6925 
6926 	/*
6927 	 * Transport any pending commands to the target.
6928 	 *
6929 	 * If this is a low-activity device commands in queue will have to wait
6930 	 * until new commands come in, which may take awhile. Also, we
6931 	 * specifically don't check un_ncmds_in_transport because we know that
6932 	 * there really are no commands in progress after the unit was
6933 	 * suspended and we could have reached the throttle level, been
6934 	 * suspended, and have no new commands coming in for awhile. Highly
6935 	 * unlikely, but so is the low-activity disk scenario.
6936 	 */
6937 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6938 
6939 	sd_start_cmds(un, NULL);
6940 	mutex_exit(SD_MUTEX(un));
6941 
6942 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6943 
6944 	return (DDI_SUCCESS);
6945 }
6946 
6947 
6948 /*
6949  *    Function: sd_ddi_pm_resume
6950  *
6951  * Description: Set the drive state to powered on.
6952  *		Someone else is required to actually change the drive
6953  *		power level.
6954  *
6955  *   Arguments: un - driver soft state (unit) structure
6956  *
6957  * Return Code: DDI_SUCCESS
6958  *
6959  *     Context: Kernel thread context
6960  */
6961 
6962 static int
6963 sd_ddi_pm_resume(struct sd_lun *un)
6964 {
6965 	ASSERT(un != NULL);
6966 
6967 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6968 	mutex_enter(SD_MUTEX(un));
6969 	un->un_power_level = SD_SPINDLE_ON;
6970 
6971 	ASSERT(!mutex_owned(&un->un_pm_mutex));
6972 	mutex_enter(&un->un_pm_mutex);
6973 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6974 		un->un_pm_count++;
6975 		ASSERT(un->un_pm_count == 0);
6976 		/*
6977 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
6978 		 * un_suspend_cv is for a system resume, not a power management
6979 		 * device resume. (4297749)
6980 		 *	 cv_broadcast(&un->un_suspend_cv);
6981 		 */
6982 	}
6983 	mutex_exit(&un->un_pm_mutex);
6984 	mutex_exit(SD_MUTEX(un));
6985 
6986 	return (DDI_SUCCESS);
6987 }
6988 
6989 
6990 /*
6991  *    Function: sd_pm_idletimeout_handler
6992  *
6993  * Description: A timer routine that's active only while a device is busy.
6994  *		The purpose is to extend slightly the pm framework's busy
6995  *		view of the device to prevent busy/idle thrashing for
6996  *		back-to-back commands. Do this by comparing the current time
6997  *		to the time at which the last command completed and when the
6998  *		difference is greater than sd_pm_idletime, call
6999  *		pm_idle_component. In addition to indicating idle to the pm
7000  *		framework, update the chain type to again use the internal pm
7001  *		layers of the driver.
7002  *
7003  *   Arguments: arg - driver soft state (unit) structure
7004  *
7005  *     Context: Executes in a timeout(9F) thread context
7006  */
7007 
7008 static void
7009 sd_pm_idletimeout_handler(void *arg)
7010 {
7011 	struct sd_lun *un = arg;
7012 
7013 	time_t	now;
7014 
7015 	mutex_enter(&sd_detach_mutex);
7016 	if (un->un_detach_count != 0) {
7017 		/* Abort if the instance is detaching */
7018 		mutex_exit(&sd_detach_mutex);
7019 		return;
7020 	}
7021 	mutex_exit(&sd_detach_mutex);
7022 
7023 	now = ddi_get_time();
7024 	/*
7025 	 * Grab both mutexes, in the proper order, since we're accessing
7026 	 * both PM and softstate variables.
7027 	 */
7028 	mutex_enter(SD_MUTEX(un));
7029 	mutex_enter(&un->un_pm_mutex);
7030 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
7031 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
7032 		/*
7033 		 * Update the chain types.
7034 		 * This takes affect on the next new command received.
7035 		 */
7036 		if (un->un_f_non_devbsize_supported) {
7037 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7038 		} else {
7039 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7040 		}
7041 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7042 
7043 		SD_TRACE(SD_LOG_IO_PM, un,
7044 		    "sd_pm_idletimeout_handler: idling device\n");
7045 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7046 		un->un_pm_idle_timeid = NULL;
7047 	} else {
7048 		un->un_pm_idle_timeid =
7049 			timeout(sd_pm_idletimeout_handler, un,
7050 			(drv_usectohz((clock_t)300000))); /* 300 ms. */
7051 	}
7052 	mutex_exit(&un->un_pm_mutex);
7053 	mutex_exit(SD_MUTEX(un));
7054 }
7055 
7056 
7057 /*
7058  *    Function: sd_pm_timeout_handler
7059  *
7060  * Description: Callback to tell framework we are idle.
7061  *
7062  *     Context: timeout(9f) thread context.
7063  */
7064 
7065 static void
7066 sd_pm_timeout_handler(void *arg)
7067 {
7068 	struct sd_lun *un = arg;
7069 
7070 	(void) pm_idle_component(SD_DEVINFO(un), 0);
7071 	mutex_enter(&un->un_pm_mutex);
7072 	un->un_pm_timeid = NULL;
7073 	mutex_exit(&un->un_pm_mutex);
7074 }
7075 
7076 
7077 /*
7078  *    Function: sdpower
7079  *
7080  * Description: PM entry point.
7081  *
7082  * Return Code: DDI_SUCCESS
7083  *		DDI_FAILURE
7084  *
7085  *     Context: Kernel thread context
7086  */
7087 
7088 static int
7089 sdpower(dev_info_t *devi, int component, int level)
7090 {
7091 	struct sd_lun	*un;
7092 	int		instance;
7093 	int		rval = DDI_SUCCESS;
7094 	uint_t		i, log_page_size, maxcycles, ncycles;
7095 	uchar_t		*log_page_data;
7096 	int		log_sense_page;
7097 	int		medium_present;
7098 	time_t		intvlp;
7099 	dev_t		dev;
7100 	struct pm_trans_data	sd_pm_tran_data;
7101 	uchar_t		save_state;
7102 	int		sval;
7103 	uchar_t		state_before_pm;
7104 	int		got_semaphore_here;
7105 
7106 	instance = ddi_get_instance(devi);
7107 
7108 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
7109 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
7110 	    component != 0) {
7111 		return (DDI_FAILURE);
7112 	}
7113 
7114 	dev = sd_make_device(SD_DEVINFO(un));
7115 
7116 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
7117 
7118 	/*
7119 	 * Must synchronize power down with close.
7120 	 * Attempt to decrement/acquire the open/close semaphore,
7121 	 * but do NOT wait on it. If it's not greater than zero,
7122 	 * ie. it can't be decremented without waiting, then
7123 	 * someone else, either open or close, already has it
7124 	 * and the try returns 0. Use that knowledge here to determine
7125 	 * if it's OK to change the device power level.
7126 	 * Also, only increment it on exit if it was decremented, ie. gotten,
7127 	 * here.
7128 	 */
7129 	got_semaphore_here = sema_tryp(&un->un_semoclose);
7130 
7131 	mutex_enter(SD_MUTEX(un));
7132 
7133 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
7134 	    un->un_ncmds_in_driver);
7135 
7136 	/*
7137 	 * If un_ncmds_in_driver is non-zero it indicates commands are
7138 	 * already being processed in the driver, or if the semaphore was
7139 	 * not gotten here it indicates an open or close is being processed.
7140 	 * At the same time somebody is requesting to go low power which
7141 	 * can't happen, therefore we need to return failure.
7142 	 */
7143 	if ((level == SD_SPINDLE_OFF) &&
7144 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
7145 		mutex_exit(SD_MUTEX(un));
7146 
7147 		if (got_semaphore_here != 0) {
7148 			sema_v(&un->un_semoclose);
7149 		}
7150 		SD_TRACE(SD_LOG_IO_PM, un,
7151 		    "sdpower: exit, device has queued cmds.\n");
7152 		return (DDI_FAILURE);
7153 	}
7154 
7155 	/*
7156 	 * if it is OFFLINE that means the disk is completely dead
7157 	 * in our case we have to put the disk in on or off by sending commands
7158 	 * Of course that will fail anyway so return back here.
7159 	 *
7160 	 * Power changes to a device that's OFFLINE or SUSPENDED
7161 	 * are not allowed.
7162 	 */
7163 	if ((un->un_state == SD_STATE_OFFLINE) ||
7164 	    (un->un_state == SD_STATE_SUSPENDED)) {
7165 		mutex_exit(SD_MUTEX(un));
7166 
7167 		if (got_semaphore_here != 0) {
7168 			sema_v(&un->un_semoclose);
7169 		}
7170 		SD_TRACE(SD_LOG_IO_PM, un,
7171 		    "sdpower: exit, device is off-line.\n");
7172 		return (DDI_FAILURE);
7173 	}
7174 
7175 	/*
7176 	 * Change the device's state to indicate it's power level
7177 	 * is being changed. Do this to prevent a power off in the
7178 	 * middle of commands, which is especially bad on devices
7179 	 * that are really powered off instead of just spun down.
7180 	 */
7181 	state_before_pm = un->un_state;
7182 	un->un_state = SD_STATE_PM_CHANGING;
7183 
7184 	mutex_exit(SD_MUTEX(un));
7185 
7186 	/*
7187 	 * If "pm-capable" property is set to TRUE by HBA drivers,
7188 	 * bypass the following checking, otherwise, check the log
7189 	 * sense information for this device
7190 	 */
7191 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
7192 		/*
7193 		 * Get the log sense information to understand whether the
7194 		 * the powercycle counts have gone beyond the threshhold.
7195 		 */
7196 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
7197 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
7198 
7199 		mutex_enter(SD_MUTEX(un));
7200 		log_sense_page = un->un_start_stop_cycle_page;
7201 		mutex_exit(SD_MUTEX(un));
7202 
7203 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
7204 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
7205 #ifdef	SDDEBUG
7206 		if (sd_force_pm_supported) {
7207 			/* Force a successful result */
7208 			rval = 0;
7209 		}
7210 #endif
7211 		if (rval != 0) {
7212 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
7213 			    "Log Sense Failed\n");
7214 			kmem_free(log_page_data, log_page_size);
7215 			/* Cannot support power management on those drives */
7216 
7217 			if (got_semaphore_here != 0) {
7218 				sema_v(&un->un_semoclose);
7219 			}
7220 			/*
7221 			 * On exit put the state back to it's original value
7222 			 * and broadcast to anyone waiting for the power
7223 			 * change completion.
7224 			 */
7225 			mutex_enter(SD_MUTEX(un));
7226 			un->un_state = state_before_pm;
7227 			cv_broadcast(&un->un_suspend_cv);
7228 			mutex_exit(SD_MUTEX(un));
7229 			SD_TRACE(SD_LOG_IO_PM, un,
7230 			    "sdpower: exit, Log Sense Failed.\n");
7231 			return (DDI_FAILURE);
7232 		}
7233 
7234 		/*
7235 		 * From the page data - Convert the essential information to
7236 		 * pm_trans_data
7237 		 */
7238 		maxcycles =
7239 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
7240 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
7241 
7242 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
7243 
7244 		ncycles =
7245 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
7246 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
7247 
7248 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
7249 
7250 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
7251 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
7252 			    log_page_data[8+i];
7253 		}
7254 
7255 		kmem_free(log_page_data, log_page_size);
7256 
7257 		/*
7258 		 * Call pm_trans_check routine to get the Ok from
7259 		 * the global policy
7260 		 */
7261 
7262 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
7263 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
7264 
7265 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
7266 #ifdef	SDDEBUG
7267 		if (sd_force_pm_supported) {
7268 			/* Force a successful result */
7269 			rval = 1;
7270 		}
7271 #endif
7272 		switch (rval) {
7273 		case 0:
7274 			/*
7275 			 * Not Ok to Power cycle or error in parameters passed
7276 			 * Would have given the advised time to consider power
7277 			 * cycle. Based on the new intvlp parameter we are
7278 			 * supposed to pretend we are busy so that pm framework
7279 			 * will never call our power entry point. Because of
7280 			 * that install a timeout handler and wait for the
7281 			 * recommended time to elapse so that power management
7282 			 * can be effective again.
7283 			 *
7284 			 * To effect this behavior, call pm_busy_component to
7285 			 * indicate to the framework this device is busy.
7286 			 * By not adjusting un_pm_count the rest of PM in
7287 			 * the driver will function normally, and independant
7288 			 * of this but because the framework is told the device
7289 			 * is busy it won't attempt powering down until it gets
7290 			 * a matching idle. The timeout handler sends this.
7291 			 * Note: sd_pm_entry can't be called here to do this
7292 			 * because sdpower may have been called as a result
7293 			 * of a call to pm_raise_power from within sd_pm_entry.
7294 			 *
7295 			 * If a timeout handler is already active then
7296 			 * don't install another.
7297 			 */
7298 			mutex_enter(&un->un_pm_mutex);
7299 			if (un->un_pm_timeid == NULL) {
7300 				un->un_pm_timeid =
7301 				    timeout(sd_pm_timeout_handler,
7302 				    un, intvlp * drv_usectohz(1000000));
7303 				mutex_exit(&un->un_pm_mutex);
7304 				(void) pm_busy_component(SD_DEVINFO(un), 0);
7305 			} else {
7306 				mutex_exit(&un->un_pm_mutex);
7307 			}
7308 			if (got_semaphore_here != 0) {
7309 				sema_v(&un->un_semoclose);
7310 			}
7311 			/*
7312 			 * On exit put the state back to it's original value
7313 			 * and broadcast to anyone waiting for the power
7314 			 * change completion.
7315 			 */
7316 			mutex_enter(SD_MUTEX(un));
7317 			un->un_state = state_before_pm;
7318 			cv_broadcast(&un->un_suspend_cv);
7319 			mutex_exit(SD_MUTEX(un));
7320 
7321 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
7322 			    "trans check Failed, not ok to power cycle.\n");
7323 			return (DDI_FAILURE);
7324 
7325 		case -1:
7326 			if (got_semaphore_here != 0) {
7327 				sema_v(&un->un_semoclose);
7328 			}
7329 			/*
7330 			 * On exit put the state back to it's original value
7331 			 * and broadcast to anyone waiting for the power
7332 			 * change completion.
7333 			 */
7334 			mutex_enter(SD_MUTEX(un));
7335 			un->un_state = state_before_pm;
7336 			cv_broadcast(&un->un_suspend_cv);
7337 			mutex_exit(SD_MUTEX(un));
7338 			SD_TRACE(SD_LOG_IO_PM, un,
7339 			    "sdpower: exit, trans check command Failed.\n");
7340 			return (DDI_FAILURE);
7341 		}
7342 	}
7343 
7344 	if (level == SD_SPINDLE_OFF) {
7345 		/*
7346 		 * Save the last state... if the STOP FAILS we need it
7347 		 * for restoring
7348 		 */
7349 		mutex_enter(SD_MUTEX(un));
7350 		save_state = un->un_last_state;
7351 		/*
7352 		 * There must not be any cmds. getting processed
7353 		 * in the driver when we get here. Power to the
7354 		 * device is potentially going off.
7355 		 */
7356 		ASSERT(un->un_ncmds_in_driver == 0);
7357 		mutex_exit(SD_MUTEX(un));
7358 
7359 		/*
7360 		 * For now suspend the device completely before spindle is
7361 		 * turned off
7362 		 */
7363 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
7364 			if (got_semaphore_here != 0) {
7365 				sema_v(&un->un_semoclose);
7366 			}
7367 			/*
7368 			 * On exit put the state back to it's original value
7369 			 * and broadcast to anyone waiting for the power
7370 			 * change completion.
7371 			 */
7372 			mutex_enter(SD_MUTEX(un));
7373 			un->un_state = state_before_pm;
7374 			cv_broadcast(&un->un_suspend_cv);
7375 			mutex_exit(SD_MUTEX(un));
7376 			SD_TRACE(SD_LOG_IO_PM, un,
7377 			    "sdpower: exit, PM suspend Failed.\n");
7378 			return (DDI_FAILURE);
7379 		}
7380 	}
7381 
7382 	/*
7383 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
7384 	 * close, or strategy. Dump no long uses this routine, it uses it's
7385 	 * own code so it can be done in polled mode.
7386 	 */
7387 
7388 	medium_present = TRUE;
7389 
7390 	/*
7391 	 * When powering up, issue a TUR in case the device is at unit
7392 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
7393 	 * a deadlock on un_pm_busy_cv will occur.
7394 	 */
7395 	if (level == SD_SPINDLE_ON) {
7396 		(void) sd_send_scsi_TEST_UNIT_READY(un,
7397 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
7398 	}
7399 
7400 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
7401 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
7402 
7403 	sval = sd_send_scsi_START_STOP_UNIT(un,
7404 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
7405 	    SD_PATH_DIRECT);
7406 	/* Command failed, check for media present. */
7407 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
7408 		medium_present = FALSE;
7409 	}
7410 
7411 	/*
7412 	 * The conditions of interest here are:
7413 	 *   if a spindle off with media present fails,
7414 	 *	then restore the state and return an error.
7415 	 *   else if a spindle on fails,
7416 	 *	then return an error (there's no state to restore).
7417 	 * In all other cases we setup for the new state
7418 	 * and return success.
7419 	 */
7420 	switch (level) {
7421 	case SD_SPINDLE_OFF:
7422 		if ((medium_present == TRUE) && (sval != 0)) {
7423 			/* The stop command from above failed */
7424 			rval = DDI_FAILURE;
7425 			/*
7426 			 * The stop command failed, and we have media
7427 			 * present. Put the level back by calling the
7428 			 * sd_pm_resume() and set the state back to
7429 			 * it's previous value.
7430 			 */
7431 			(void) sd_ddi_pm_resume(un);
7432 			mutex_enter(SD_MUTEX(un));
7433 			un->un_last_state = save_state;
7434 			mutex_exit(SD_MUTEX(un));
7435 			break;
7436 		}
7437 		/*
7438 		 * The stop command from above succeeded.
7439 		 */
7440 		if (un->un_f_monitor_media_state) {
7441 			/*
7442 			 * Terminate watch thread in case of removable media
7443 			 * devices going into low power state. This is as per
7444 			 * the requirements of pm framework, otherwise commands
7445 			 * will be generated for the device (through watch
7446 			 * thread), even when the device is in low power state.
7447 			 */
7448 			mutex_enter(SD_MUTEX(un));
7449 			un->un_f_watcht_stopped = FALSE;
7450 			if (un->un_swr_token != NULL) {
7451 				opaque_t temp_token = un->un_swr_token;
7452 				un->un_f_watcht_stopped = TRUE;
7453 				un->un_swr_token = NULL;
7454 				mutex_exit(SD_MUTEX(un));
7455 				(void) scsi_watch_request_terminate(temp_token,
7456 				    SCSI_WATCH_TERMINATE_WAIT);
7457 			} else {
7458 				mutex_exit(SD_MUTEX(un));
7459 			}
7460 		}
7461 		break;
7462 
7463 	default:	/* The level requested is spindle on... */
7464 		/*
7465 		 * Legacy behavior: return success on a failed spinup
7466 		 * if there is no media in the drive.
7467 		 * Do this by looking at medium_present here.
7468 		 */
7469 		if ((sval != 0) && medium_present) {
7470 			/* The start command from above failed */
7471 			rval = DDI_FAILURE;
7472 			break;
7473 		}
7474 		/*
7475 		 * The start command from above succeeded
7476 		 * Resume the devices now that we have
7477 		 * started the disks
7478 		 */
7479 		(void) sd_ddi_pm_resume(un);
7480 
7481 		/*
7482 		 * Resume the watch thread since it was suspended
7483 		 * when the device went into low power mode.
7484 		 */
7485 		if (un->un_f_monitor_media_state) {
7486 			mutex_enter(SD_MUTEX(un));
7487 			if (un->un_f_watcht_stopped == TRUE) {
7488 				opaque_t temp_token;
7489 
7490 				un->un_f_watcht_stopped = FALSE;
7491 				mutex_exit(SD_MUTEX(un));
7492 				temp_token = scsi_watch_request_submit(
7493 				    SD_SCSI_DEVP(un),
7494 				    sd_check_media_time,
7495 				    SENSE_LENGTH, sd_media_watch_cb,
7496 				    (caddr_t)dev);
7497 				mutex_enter(SD_MUTEX(un));
7498 				un->un_swr_token = temp_token;
7499 			}
7500 			mutex_exit(SD_MUTEX(un));
7501 		}
7502 	}
7503 	if (got_semaphore_here != 0) {
7504 		sema_v(&un->un_semoclose);
7505 	}
7506 	/*
7507 	 * On exit put the state back to it's original value
7508 	 * and broadcast to anyone waiting for the power
7509 	 * change completion.
7510 	 */
7511 	mutex_enter(SD_MUTEX(un));
7512 	un->un_state = state_before_pm;
7513 	cv_broadcast(&un->un_suspend_cv);
7514 	mutex_exit(SD_MUTEX(un));
7515 
7516 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
7517 
7518 	return (rval);
7519 }
7520 
7521 
7522 
7523 /*
7524  *    Function: sdattach
7525  *
7526  * Description: Driver's attach(9e) entry point function.
7527  *
7528  *   Arguments: devi - opaque device info handle
7529  *		cmd  - attach  type
7530  *
7531  * Return Code: DDI_SUCCESS
7532  *		DDI_FAILURE
7533  *
7534  *     Context: Kernel thread context
7535  */
7536 
7537 static int
7538 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7539 {
7540 	switch (cmd) {
7541 	case DDI_ATTACH:
7542 		return (sd_unit_attach(devi));
7543 	case DDI_RESUME:
7544 		return (sd_ddi_resume(devi));
7545 	default:
7546 		break;
7547 	}
7548 	return (DDI_FAILURE);
7549 }
7550 
7551 
7552 /*
7553  *    Function: sddetach
7554  *
7555  * Description: Driver's detach(9E) entry point function.
7556  *
7557  *   Arguments: devi - opaque device info handle
7558  *		cmd  - detach  type
7559  *
7560  * Return Code: DDI_SUCCESS
7561  *		DDI_FAILURE
7562  *
7563  *     Context: Kernel thread context
7564  */
7565 
7566 static int
7567 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7568 {
7569 	switch (cmd) {
7570 	case DDI_DETACH:
7571 		return (sd_unit_detach(devi));
7572 	case DDI_SUSPEND:
7573 		return (sd_ddi_suspend(devi));
7574 	default:
7575 		break;
7576 	}
7577 	return (DDI_FAILURE);
7578 }
7579 
7580 
7581 /*
7582  *     Function: sd_sync_with_callback
7583  *
7584  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7585  *		 state while the callback routine is active.
7586  *
7587  *    Arguments: un: softstate structure for the instance
7588  *
7589  *	Context: Kernel thread context
7590  */
7591 
7592 static void
7593 sd_sync_with_callback(struct sd_lun *un)
7594 {
7595 	ASSERT(un != NULL);
7596 
7597 	mutex_enter(SD_MUTEX(un));
7598 
7599 	ASSERT(un->un_in_callback >= 0);
7600 
7601 	while (un->un_in_callback > 0) {
7602 		mutex_exit(SD_MUTEX(un));
7603 		delay(2);
7604 		mutex_enter(SD_MUTEX(un));
7605 	}
7606 
7607 	mutex_exit(SD_MUTEX(un));
7608 }
7609 
7610 /*
7611  *    Function: sd_unit_attach
7612  *
7613  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7614  *		the soft state structure for the device and performs
7615  *		all necessary structure and device initializations.
7616  *
7617  *   Arguments: devi: the system's dev_info_t for the device.
7618  *
7619  * Return Code: DDI_SUCCESS if attach is successful.
7620  *		DDI_FAILURE if any part of the attach fails.
7621  *
7622  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7623  *		Kernel thread context only.  Can sleep.
7624  */
7625 
7626 static int
7627 sd_unit_attach(dev_info_t *devi)
7628 {
7629 	struct	scsi_device	*devp;
7630 	struct	sd_lun		*un;
7631 	char			*variantp;
7632 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7633 	int	instance;
7634 	int	rval;
7635 	int	wc_enabled;
7636 	uint64_t	capacity;
7637 	uint_t		lbasize;
7638 
7639 	/*
7640 	 * Retrieve the target driver's private data area. This was set
7641 	 * up by the HBA.
7642 	 */
7643 	devp = ddi_get_driver_private(devi);
7644 
7645 	/*
7646 	 * Since we have no idea what state things were left in by the last
7647 	 * user of the device, set up some 'default' settings, ie. turn 'em
7648 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7649 	 * Do this before the scsi_probe, which sends an inquiry.
7650 	 * This is a fix for bug (4430280).
7651 	 * Of special importance is wide-xfer. The drive could have been left
7652 	 * in wide transfer mode by the last driver to communicate with it,
7653 	 * this includes us. If that's the case, and if the following is not
7654 	 * setup properly or we don't re-negotiate with the drive prior to
7655 	 * transferring data to/from the drive, it causes bus parity errors,
7656 	 * data overruns, and unexpected interrupts. This first occurred when
7657 	 * the fix for bug (4378686) was made.
7658 	 */
7659 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7660 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7661 	(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7662 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7663 
7664 	/*
7665 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7666 	 * This call will allocate and fill in the scsi_inquiry structure
7667 	 * and point the sd_inq member of the scsi_device structure to it.
7668 	 * If the attach succeeds, then this memory will not be de-allocated
7669 	 * (via scsi_unprobe()) until the instance is detached.
7670 	 */
7671 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7672 		goto probe_failed;
7673 	}
7674 
7675 	/*
7676 	 * Check the device type as specified in the inquiry data and
7677 	 * claim it if it is of a type that we support.
7678 	 */
7679 	switch (devp->sd_inq->inq_dtype) {
7680 	case DTYPE_DIRECT:
7681 		break;
7682 	case DTYPE_RODIRECT:
7683 		break;
7684 	case DTYPE_OPTICAL:
7685 		break;
7686 	case DTYPE_NOTPRESENT:
7687 	default:
7688 		/* Unsupported device type; fail the attach. */
7689 		goto probe_failed;
7690 	}
7691 
7692 	/*
7693 	 * Allocate the soft state structure for this unit.
7694 	 *
7695 	 * We rely upon this memory being set to all zeroes by
7696 	 * ddi_soft_state_zalloc().  We assume that any member of the
7697 	 * soft state structure that is not explicitly initialized by
7698 	 * this routine will have a value of zero.
7699 	 */
7700 	instance = ddi_get_instance(devp->sd_dev);
7701 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7702 		goto probe_failed;
7703 	}
7704 
7705 	/*
7706 	 * Retrieve a pointer to the newly-allocated soft state.
7707 	 *
7708 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7709 	 * was successful, unless something has gone horribly wrong and the
7710 	 * ddi's soft state internals are corrupt (in which case it is
7711 	 * probably better to halt here than just fail the attach....)
7712 	 */
7713 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7714 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7715 		    instance);
7716 		/*NOTREACHED*/
7717 	}
7718 
7719 	/*
7720 	 * Link the back ptr of the driver soft state to the scsi_device
7721 	 * struct for this lun.
7722 	 * Save a pointer to the softstate in the driver-private area of
7723 	 * the scsi_device struct.
7724 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7725 	 * we first set un->un_sd below.
7726 	 */
7727 	un->un_sd = devp;
7728 	devp->sd_private = (opaque_t)un;
7729 
7730 	/*
7731 	 * The following must be after devp is stored in the soft state struct.
7732 	 */
7733 #ifdef SDDEBUG
7734 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7735 	    "%s_unit_attach: un:0x%p instance:%d\n",
7736 	    ddi_driver_name(devi), un, instance);
7737 #endif
7738 
7739 	/*
7740 	 * Set up the device type and node type (for the minor nodes).
7741 	 * By default we assume that the device can at least support the
7742 	 * Common Command Set. Call it a CD-ROM if it reports itself
7743 	 * as a RODIRECT device.
7744 	 */
7745 	switch (devp->sd_inq->inq_dtype) {
7746 	case DTYPE_RODIRECT:
7747 		un->un_node_type = DDI_NT_CD_CHAN;
7748 		un->un_ctype	 = CTYPE_CDROM;
7749 		break;
7750 	case DTYPE_OPTICAL:
7751 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7752 		un->un_ctype	 = CTYPE_ROD;
7753 		break;
7754 	default:
7755 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7756 		un->un_ctype	 = CTYPE_CCS;
7757 		break;
7758 	}
7759 
7760 	/*
7761 	 * Try to read the interconnect type from the HBA.
7762 	 *
7763 	 * Note: This driver is currently compiled as two binaries, a parallel
7764 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7765 	 * differences are determined at compile time. In the future a single
7766 	 * binary will be provided and the inteconnect type will be used to
7767 	 * differentiate between fibre and parallel scsi behaviors. At that time
7768 	 * it will be necessary for all fibre channel HBAs to support this
7769 	 * property.
7770 	 *
7771 	 * set un_f_is_fiber to TRUE ( default fiber )
7772 	 */
7773 	un->un_f_is_fibre = TRUE;
7774 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7775 	case INTERCONNECT_SSA:
7776 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7777 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7778 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7779 		break;
7780 	case INTERCONNECT_PARALLEL:
7781 		un->un_f_is_fibre = FALSE;
7782 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7783 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7784 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7785 		break;
7786 	case INTERCONNECT_FIBRE:
7787 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7788 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7789 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7790 		break;
7791 	case INTERCONNECT_FABRIC:
7792 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7793 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7794 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7795 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7796 		break;
7797 	default:
7798 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7799 		/*
7800 		 * The HBA does not support the "interconnect-type" property
7801 		 * (or did not provide a recognized type).
7802 		 *
7803 		 * Note: This will be obsoleted when a single fibre channel
7804 		 * and parallel scsi driver is delivered. In the meantime the
7805 		 * interconnect type will be set to the platform default.If that
7806 		 * type is not parallel SCSI, it means that we should be
7807 		 * assuming "ssd" semantics. However, here this also means that
7808 		 * the FC HBA is not supporting the "interconnect-type" property
7809 		 * like we expect it to, so log this occurrence.
7810 		 */
7811 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7812 		if (!SD_IS_PARALLEL_SCSI(un)) {
7813 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7814 			    "sd_unit_attach: un:0x%p Assuming "
7815 			    "INTERCONNECT_FIBRE\n", un);
7816 		} else {
7817 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7818 			    "sd_unit_attach: un:0x%p Assuming "
7819 			    "INTERCONNECT_PARALLEL\n", un);
7820 			un->un_f_is_fibre = FALSE;
7821 		}
7822 #else
7823 		/*
7824 		 * Note: This source will be implemented when a single fibre
7825 		 * channel and parallel scsi driver is delivered. The default
7826 		 * will be to assume that if a device does not support the
7827 		 * "interconnect-type" property it is a parallel SCSI HBA and
7828 		 * we will set the interconnect type for parallel scsi.
7829 		 */
7830 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7831 		un->un_f_is_fibre = FALSE;
7832 #endif
7833 		break;
7834 	}
7835 
7836 	if (un->un_f_is_fibre == TRUE) {
7837 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7838 			SCSI_VERSION_3) {
7839 			switch (un->un_interconnect_type) {
7840 			case SD_INTERCONNECT_FIBRE:
7841 			case SD_INTERCONNECT_SSA:
7842 				un->un_node_type = DDI_NT_BLOCK_WWN;
7843 				break;
7844 			default:
7845 				break;
7846 			}
7847 		}
7848 	}
7849 
7850 	/*
7851 	 * Initialize the Request Sense command for the target
7852 	 */
7853 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7854 		goto alloc_rqs_failed;
7855 	}
7856 
7857 	/*
7858 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7859 	 * with seperate binary for sd and ssd.
7860 	 *
7861 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7862 	 * The hardcoded values will go away when Sparc uses 1 binary
7863 	 * for sd and ssd.  This hardcoded values need to match
7864 	 * SD_RETRY_COUNT in sddef.h
7865 	 * The value used is base on interconnect type.
7866 	 * fibre = 3, parallel = 5
7867 	 */
7868 #if defined(__i386) || defined(__amd64)
7869 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7870 #else
7871 	un->un_retry_count = SD_RETRY_COUNT;
7872 #endif
7873 
7874 	/*
7875 	 * Set the per disk retry count to the default number of retries
7876 	 * for disks and CDROMs. This value can be overridden by the
7877 	 * disk property list or an entry in sd.conf.
7878 	 */
7879 	un->un_notready_retry_count =
7880 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7881 			: DISK_NOT_READY_RETRY_COUNT(un);
7882 
7883 	/*
7884 	 * Set the busy retry count to the default value of un_retry_count.
7885 	 * This can be overridden by entries in sd.conf or the device
7886 	 * config table.
7887 	 */
7888 	un->un_busy_retry_count = un->un_retry_count;
7889 
7890 	/*
7891 	 * Init the reset threshold for retries.  This number determines
7892 	 * how many retries must be performed before a reset can be issued
7893 	 * (for certain error conditions). This can be overridden by entries
7894 	 * in sd.conf or the device config table.
7895 	 */
7896 	un->un_reset_retry_count = (un->un_retry_count / 2);
7897 
7898 	/*
7899 	 * Set the victim_retry_count to the default un_retry_count
7900 	 */
7901 	un->un_victim_retry_count = (2 * un->un_retry_count);
7902 
7903 	/*
7904 	 * Set the reservation release timeout to the default value of
7905 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7906 	 * device config table.
7907 	 */
7908 	un->un_reserve_release_time = 5;
7909 
7910 	/*
7911 	 * Set up the default maximum transfer size. Note that this may
7912 	 * get updated later in the attach, when setting up default wide
7913 	 * operations for disks.
7914 	 */
7915 #if defined(__i386) || defined(__amd64)
7916 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7917 #else
7918 	un->un_max_xfer_size = (uint_t)maxphys;
7919 #endif
7920 
7921 	/*
7922 	 * Get "allow bus device reset" property (defaults to "enabled" if
7923 	 * the property was not defined). This is to disable bus resets for
7924 	 * certain kinds of error recovery. Note: In the future when a run-time
7925 	 * fibre check is available the soft state flag should default to
7926 	 * enabled.
7927 	 */
7928 	if (un->un_f_is_fibre == TRUE) {
7929 		un->un_f_allow_bus_device_reset = TRUE;
7930 	} else {
7931 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7932 			"allow-bus-device-reset", 1) != 0) {
7933 			un->un_f_allow_bus_device_reset = TRUE;
7934 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7935 			"sd_unit_attach: un:0x%p Bus device reset enabled\n",
7936 				un);
7937 		} else {
7938 			un->un_f_allow_bus_device_reset = FALSE;
7939 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7940 			"sd_unit_attach: un:0x%p Bus device reset disabled\n",
7941 				un);
7942 		}
7943 	}
7944 
7945 	/*
7946 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7947 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7948 	 *
7949 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7950 	 * property. The new "variant" property with a value of "atapi" has been
7951 	 * introduced so that future 'variants' of standard SCSI behavior (like
7952 	 * atapi) could be specified by the underlying HBA drivers by supplying
7953 	 * a new value for the "variant" property, instead of having to define a
7954 	 * new property.
7955 	 */
7956 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7957 		un->un_f_cfg_is_atapi = TRUE;
7958 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7959 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7960 	}
7961 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7962 	    &variantp) == DDI_PROP_SUCCESS) {
7963 		if (strcmp(variantp, "atapi") == 0) {
7964 			un->un_f_cfg_is_atapi = TRUE;
7965 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7966 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7967 		}
7968 		ddi_prop_free(variantp);
7969 	}
7970 
7971 	un->un_cmd_timeout	= SD_IO_TIME;
7972 
7973 	/* Info on current states, statuses, etc. (Updated frequently) */
7974 	un->un_state		= SD_STATE_NORMAL;
7975 	un->un_last_state	= SD_STATE_NORMAL;
7976 
7977 	/* Control & status info for command throttling */
7978 	un->un_throttle		= sd_max_throttle;
7979 	un->un_saved_throttle	= sd_max_throttle;
7980 	un->un_min_throttle	= sd_min_throttle;
7981 
7982 	if (un->un_f_is_fibre == TRUE) {
7983 		un->un_f_use_adaptive_throttle = TRUE;
7984 	} else {
7985 		un->un_f_use_adaptive_throttle = FALSE;
7986 	}
7987 
7988 	/* Removable media support. */
7989 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7990 	un->un_mediastate		= DKIO_NONE;
7991 	un->un_specified_mediastate	= DKIO_NONE;
7992 
7993 	/* CVs for suspend/resume (PM or DR) */
7994 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7995 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7996 
7997 	/* Power management support. */
7998 	un->un_power_level = SD_SPINDLE_UNINIT;
7999 
8000 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
8001 	un->un_f_wcc_inprog = 0;
8002 
8003 	/*
8004 	 * The open/close semaphore is used to serialize threads executing
8005 	 * in the driver's open & close entry point routines for a given
8006 	 * instance.
8007 	 */
8008 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
8009 
8010 	/*
8011 	 * The conf file entry and softstate variable is a forceful override,
8012 	 * meaning a non-zero value must be entered to change the default.
8013 	 */
8014 	un->un_f_disksort_disabled = FALSE;
8015 
8016 	/*
8017 	 * Retrieve the properties from the static driver table or the driver
8018 	 * configuration file (.conf) for this unit and update the soft state
8019 	 * for the device as needed for the indicated properties.
8020 	 * Note: the property configuration needs to occur here as some of the
8021 	 * following routines may have dependancies on soft state flags set
8022 	 * as part of the driver property configuration.
8023 	 */
8024 	sd_read_unit_properties(un);
8025 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8026 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
8027 
8028 	/*
8029 	 * Only if a device has "hotpluggable" property, it is
8030 	 * treated as hotpluggable device. Otherwise, it is
8031 	 * regarded as non-hotpluggable one.
8032 	 */
8033 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
8034 	    -1) != -1) {
8035 		un->un_f_is_hotpluggable = TRUE;
8036 	}
8037 
8038 	/*
8039 	 * set unit's attributes(flags) according to "hotpluggable" and
8040 	 * RMB bit in INQUIRY data.
8041 	 */
8042 	sd_set_unit_attributes(un, devi);
8043 
8044 	/*
8045 	 * By default, we mark the capacity, lbasize, and geometry
8046 	 * as invalid. Only if we successfully read a valid capacity
8047 	 * will we update the un_blockcount and un_tgt_blocksize with the
8048 	 * valid values (the geometry will be validated later).
8049 	 */
8050 	un->un_f_blockcount_is_valid	= FALSE;
8051 	un->un_f_tgt_blocksize_is_valid	= FALSE;
8052 	un->un_f_geometry_is_valid	= FALSE;
8053 
8054 	/*
8055 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
8056 	 * otherwise.
8057 	 */
8058 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
8059 	un->un_blockcount = 0;
8060 
8061 	/*
8062 	 * Set up the per-instance info needed to determine the correct
8063 	 * CDBs and other info for issuing commands to the target.
8064 	 */
8065 	sd_init_cdb_limits(un);
8066 
8067 	/*
8068 	 * Set up the IO chains to use, based upon the target type.
8069 	 */
8070 	if (un->un_f_non_devbsize_supported) {
8071 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
8072 	} else {
8073 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
8074 	}
8075 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
8076 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
8077 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
8078 
8079 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
8080 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
8081 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
8082 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
8083 
8084 
8085 	if (ISCD(un)) {
8086 		un->un_additional_codes = sd_additional_codes;
8087 	} else {
8088 		un->un_additional_codes = NULL;
8089 	}
8090 
8091 	/*
8092 	 * Create the kstats here so they can be available for attach-time
8093 	 * routines that send commands to the unit (either polled or via
8094 	 * sd_send_scsi_cmd).
8095 	 *
8096 	 * Note: This is a critical sequence that needs to be maintained:
8097 	 *	1) Instantiate the kstats here, before any routines using the
8098 	 *	   iopath (i.e. sd_send_scsi_cmd).
8099 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8100 	 *	   stats (sd_set_pstats), following sd_validate_geometry(),
8101 	 *	   sd_register_devid(), and sd_cache_control().
8102 	 */
8103 
8104 	un->un_stats = kstat_create(sd_label, instance,
8105 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
8106 	if (un->un_stats != NULL) {
8107 		un->un_stats->ks_lock = SD_MUTEX(un);
8108 		kstat_install(un->un_stats);
8109 	}
8110 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8111 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
8112 
8113 	sd_create_errstats(un, instance);
8114 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8115 	    "sd_unit_attach: un:0x%p errstats created\n", un);
8116 
8117 	/*
8118 	 * The following if/else code was relocated here from below as part
8119 	 * of the fix for bug (4430280). However with the default setup added
8120 	 * on entry to this routine, it's no longer absolutely necessary for
8121 	 * this to be before the call to sd_spin_up_unit.
8122 	 */
8123 	if (SD_IS_PARALLEL_SCSI(un)) {
8124 		/*
8125 		 * If SCSI-2 tagged queueing is supported by the target
8126 		 * and by the host adapter then we will enable it.
8127 		 */
8128 		un->un_tagflags = 0;
8129 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
8130 		    (devp->sd_inq->inq_cmdque) &&
8131 		    (un->un_f_arq_enabled == TRUE)) {
8132 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
8133 			    1, 1) == 1) {
8134 				un->un_tagflags = FLAG_STAG;
8135 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8136 				    "sd_unit_attach: un:0x%p tag queueing "
8137 				    "enabled\n", un);
8138 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
8139 			    "untagged-qing", 0) == 1) {
8140 				un->un_f_opt_queueing = TRUE;
8141 				un->un_saved_throttle = un->un_throttle =
8142 				    min(un->un_throttle, 3);
8143 			} else {
8144 				un->un_f_opt_queueing = FALSE;
8145 				un->un_saved_throttle = un->un_throttle = 1;
8146 			}
8147 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
8148 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
8149 			/* The Host Adapter supports internal queueing. */
8150 			un->un_f_opt_queueing = TRUE;
8151 			un->un_saved_throttle = un->un_throttle =
8152 			    min(un->un_throttle, 3);
8153 		} else {
8154 			un->un_f_opt_queueing = FALSE;
8155 			un->un_saved_throttle = un->un_throttle = 1;
8156 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8157 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
8158 		}
8159 
8160 
8161 		/* Setup or tear down default wide operations for disks */
8162 
8163 		/*
8164 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
8165 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
8166 		 * system and be set to different values. In the future this
8167 		 * code may need to be updated when the ssd module is
8168 		 * obsoleted and removed from the system. (4299588)
8169 		 */
8170 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
8171 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
8172 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
8173 			    1, 1) == 1) {
8174 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8175 				    "sd_unit_attach: un:0x%p Wide Transfer "
8176 				    "enabled\n", un);
8177 			}
8178 
8179 			/*
8180 			 * If tagged queuing has also been enabled, then
8181 			 * enable large xfers
8182 			 */
8183 			if (un->un_saved_throttle == sd_max_throttle) {
8184 				un->un_max_xfer_size =
8185 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8186 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
8187 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8188 				    "sd_unit_attach: un:0x%p max transfer "
8189 				    "size=0x%x\n", un, un->un_max_xfer_size);
8190 			}
8191 		} else {
8192 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
8193 			    0, 1) == 1) {
8194 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8195 				    "sd_unit_attach: un:0x%p "
8196 				    "Wide Transfer disabled\n", un);
8197 			}
8198 		}
8199 	} else {
8200 		un->un_tagflags = FLAG_STAG;
8201 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
8202 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
8203 	}
8204 
8205 	/*
8206 	 * If this target supports LUN reset, try to enable it.
8207 	 */
8208 	if (un->un_f_lun_reset_enabled) {
8209 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
8210 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
8211 			    "un:0x%p lun_reset capability set\n", un);
8212 		} else {
8213 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
8214 			    "un:0x%p lun-reset capability not set\n", un);
8215 		}
8216 	}
8217 
8218 	/*
8219 	 * At this point in the attach, we have enough info in the
8220 	 * soft state to be able to issue commands to the target.
8221 	 *
8222 	 * All command paths used below MUST issue their commands as
8223 	 * SD_PATH_DIRECT. This is important as intermediate layers
8224 	 * are not all initialized yet (such as PM).
8225 	 */
8226 
8227 	/*
8228 	 * Send a TEST UNIT READY command to the device. This should clear
8229 	 * any outstanding UNIT ATTENTION that may be present.
8230 	 *
8231 	 * Note: Don't check for success, just track if there is a reservation,
8232 	 * this is a throw away command to clear any unit attentions.
8233 	 *
8234 	 * Note: This MUST be the first command issued to the target during
8235 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
8236 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
8237 	 * with attempts at spinning up a device with no media.
8238 	 */
8239 	if (sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR) == EACCES) {
8240 		reservation_flag = SD_TARGET_IS_RESERVED;
8241 	}
8242 
8243 	/*
8244 	 * If the device is NOT a removable media device, attempt to spin
8245 	 * it up (using the START_STOP_UNIT command) and read its capacity
8246 	 * (using the READ CAPACITY command).  Note, however, that either
8247 	 * of these could fail and in some cases we would continue with
8248 	 * the attach despite the failure (see below).
8249 	 */
8250 	if (un->un_f_descr_format_supported) {
8251 		switch (sd_spin_up_unit(un)) {
8252 		case 0:
8253 			/*
8254 			 * Spin-up was successful; now try to read the
8255 			 * capacity.  If successful then save the results
8256 			 * and mark the capacity & lbasize as valid.
8257 			 */
8258 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8259 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
8260 
8261 			switch (sd_send_scsi_READ_CAPACITY(un, &capacity,
8262 			    &lbasize, SD_PATH_DIRECT)) {
8263 			case 0: {
8264 				if (capacity > DK_MAX_BLOCKS) {
8265 #ifdef _LP64
8266 					/*
8267 					 * Enable descriptor format sense data
8268 					 * so that we can get 64 bit sense
8269 					 * data fields.
8270 					 */
8271 					sd_enable_descr_sense(un);
8272 #else
8273 					/* 32-bit kernels can't handle this */
8274 					scsi_log(SD_DEVINFO(un),
8275 					    sd_label, CE_WARN,
8276 					    "disk has %llu blocks, which "
8277 					    "is too large for a 32-bit "
8278 					    "kernel", capacity);
8279 					goto spinup_failed;
8280 #endif
8281 				}
8282 				/*
8283 				 * The following relies on
8284 				 * sd_send_scsi_READ_CAPACITY never
8285 				 * returning 0 for capacity and/or lbasize.
8286 				 */
8287 				sd_update_block_info(un, lbasize, capacity);
8288 
8289 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8290 				    "sd_unit_attach: un:0x%p capacity = %ld "
8291 				    "blocks; lbasize= %ld.\n", un,
8292 				    un->un_blockcount, un->un_tgt_blocksize);
8293 
8294 				break;
8295 			}
8296 			case EACCES:
8297 				/*
8298 				 * Should never get here if the spin-up
8299 				 * succeeded, but code it in anyway.
8300 				 * From here, just continue with the attach...
8301 				 */
8302 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8303 				    "sd_unit_attach: un:0x%p "
8304 				    "sd_send_scsi_READ_CAPACITY "
8305 				    "returned reservation conflict\n", un);
8306 				reservation_flag = SD_TARGET_IS_RESERVED;
8307 				break;
8308 			default:
8309 				/*
8310 				 * Likewise, should never get here if the
8311 				 * spin-up succeeded. Just continue with
8312 				 * the attach...
8313 				 */
8314 				break;
8315 			}
8316 			break;
8317 		case EACCES:
8318 			/*
8319 			 * Device is reserved by another host.  In this case
8320 			 * we could not spin it up or read the capacity, but
8321 			 * we continue with the attach anyway.
8322 			 */
8323 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8324 			    "sd_unit_attach: un:0x%p spin-up reservation "
8325 			    "conflict.\n", un);
8326 			reservation_flag = SD_TARGET_IS_RESERVED;
8327 			break;
8328 		default:
8329 			/* Fail the attach if the spin-up failed. */
8330 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8331 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8332 			goto spinup_failed;
8333 		}
8334 	}
8335 
8336 	/*
8337 	 * Check to see if this is a MMC drive
8338 	 */
8339 	if (ISCD(un)) {
8340 		sd_set_mmc_caps(un);
8341 	}
8342 
8343 	/*
8344 	 * Create the minor nodes for the device.
8345 	 * Note: If we want to support fdisk on both sparc and intel, this will
8346 	 * have to separate out the notion that VTOC8 is always sparc, and
8347 	 * VTOC16 is always intel (tho these can be the defaults).  The vtoc
8348 	 * type will have to be determined at run-time, and the fdisk
8349 	 * partitioning will have to have been read & set up before we
8350 	 * create the minor nodes. (any other inits (such as kstats) that
8351 	 * also ought to be done before creating the minor nodes?) (Doesn't
8352 	 * setting up the minor nodes kind of imply that we're ready to
8353 	 * handle an open from userland?)
8354 	 */
8355 	if (sd_create_minor_nodes(un, devi) != DDI_SUCCESS) {
8356 		goto create_minor_nodes_failed;
8357 	}
8358 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8359 	    "sd_unit_attach: un:0x%p minor nodes created\n", un);
8360 
8361 	/*
8362 	 * Add a zero-length attribute to tell the world we support
8363 	 * kernel ioctls (for layered drivers)
8364 	 */
8365 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8366 	    DDI_KERNEL_IOCTL, NULL, 0);
8367 
8368 	/*
8369 	 * Add a boolean property to tell the world we support
8370 	 * the B_FAILFAST flag (for layered drivers)
8371 	 */
8372 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8373 	    "ddi-failfast-supported", NULL, 0);
8374 
8375 	/*
8376 	 * Initialize power management
8377 	 */
8378 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8379 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8380 	sd_setup_pm(un, devi);
8381 	if (un->un_f_pm_is_enabled == FALSE) {
8382 		/*
8383 		 * For performance, point to a jump table that does
8384 		 * not include pm.
8385 		 * The direct and priority chains don't change with PM.
8386 		 *
8387 		 * Note: this is currently done based on individual device
8388 		 * capabilities. When an interface for determining system
8389 		 * power enabled state becomes available, or when additional
8390 		 * layers are added to the command chain, these values will
8391 		 * have to be re-evaluated for correctness.
8392 		 */
8393 		if (un->un_f_non_devbsize_supported) {
8394 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8395 		} else {
8396 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8397 		}
8398 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8399 	}
8400 
8401 	/*
8402 	 * This property is set to 0 by HA software to avoid retries
8403 	 * on a reserved disk. (The preferred property name is
8404 	 * "retry-on-reservation-conflict") (1189689)
8405 	 *
8406 	 * Note: The use of a global here can have unintended consequences. A
8407 	 * per instance variable is preferrable to match the capabilities of
8408 	 * different underlying hba's (4402600)
8409 	 */
8410 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8411 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8412 	    sd_retry_on_reservation_conflict);
8413 	if (sd_retry_on_reservation_conflict != 0) {
8414 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8415 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8416 		    sd_retry_on_reservation_conflict);
8417 	}
8418 
8419 	/* Set up options for QFULL handling. */
8420 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8421 	    "qfull-retries", -1)) != -1) {
8422 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8423 		    rval, 1);
8424 	}
8425 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8426 	    "qfull-retry-interval", -1)) != -1) {
8427 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8428 		    rval, 1);
8429 	}
8430 
8431 	/*
8432 	 * This just prints a message that announces the existence of the
8433 	 * device. The message is always printed in the system logfile, but
8434 	 * only appears on the console if the system is booted with the
8435 	 * -v (verbose) argument.
8436 	 */
8437 	ddi_report_dev(devi);
8438 
8439 	/*
8440 	 * The framework calls driver attach routines single-threaded
8441 	 * for a given instance.  However we still acquire SD_MUTEX here
8442 	 * because this required for calling the sd_validate_geometry()
8443 	 * and sd_register_devid() functions.
8444 	 */
8445 	mutex_enter(SD_MUTEX(un));
8446 	un->un_f_geometry_is_valid = FALSE;
8447 	un->un_mediastate = DKIO_NONE;
8448 	un->un_reserved = -1;
8449 
8450 	/*
8451 	 * Read and validate the device's geometry (ie, disk label)
8452 	 * A new unformatted drive will not have a valid geometry, but
8453 	 * the driver needs to successfully attach to this device so
8454 	 * the drive can be formatted via ioctls.
8455 	 */
8456 	if (((sd_validate_geometry(un, SD_PATH_DIRECT) ==
8457 	    ENOTSUP)) &&
8458 	    (un->un_blockcount < DK_MAX_BLOCKS)) {
8459 		/*
8460 		 * We found a small disk with an EFI label on it;
8461 		 * we need to fix up the minor nodes accordingly.
8462 		 */
8463 		ddi_remove_minor_node(devi, "h");
8464 		ddi_remove_minor_node(devi, "h,raw");
8465 		(void) ddi_create_minor_node(devi, "wd",
8466 		    S_IFBLK,
8467 		    (instance << SDUNIT_SHIFT) | WD_NODE,
8468 		    un->un_node_type, NULL);
8469 		(void) ddi_create_minor_node(devi, "wd,raw",
8470 		    S_IFCHR,
8471 		    (instance << SDUNIT_SHIFT) | WD_NODE,
8472 		    un->un_node_type, NULL);
8473 	}
8474 
8475 	/*
8476 	 * Read and initialize the devid for the unit.
8477 	 */
8478 	ASSERT(un->un_errstats != NULL);
8479 	if (un->un_f_devid_supported) {
8480 		sd_register_devid(un, devi, reservation_flag);
8481 	}
8482 	mutex_exit(SD_MUTEX(un));
8483 
8484 #if (defined(__fibre))
8485 	/*
8486 	 * Register callbacks for fibre only.  You can't do this soley
8487 	 * on the basis of the devid_type because this is hba specific.
8488 	 * We need to query our hba capabilities to find out whether to
8489 	 * register or not.
8490 	 */
8491 	if (un->un_f_is_fibre) {
8492 	    if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8493 		sd_init_event_callbacks(un);
8494 		SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8495 		    "sd_unit_attach: un:0x%p event callbacks inserted", un);
8496 	    }
8497 	}
8498 #endif
8499 
8500 	if (un->un_f_opt_disable_cache == TRUE) {
8501 		/*
8502 		 * Disable both read cache and write cache.  This is
8503 		 * the historic behavior of the keywords in the config file.
8504 		 */
8505 		if (sd_cache_control(un, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8506 		    0) {
8507 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8508 			    "sd_unit_attach: un:0x%p Could not disable "
8509 			    "caching", un);
8510 			goto devid_failed;
8511 		}
8512 	}
8513 
8514 	/*
8515 	 * Check the value of the WCE bit now and
8516 	 * set un_f_write_cache_enabled accordingly.
8517 	 */
8518 	(void) sd_get_write_cache_enabled(un, &wc_enabled);
8519 	mutex_enter(SD_MUTEX(un));
8520 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8521 	mutex_exit(SD_MUTEX(un));
8522 
8523 	/*
8524 	 * Set the pstat and error stat values here, so data obtained during the
8525 	 * previous attach-time routines is available.
8526 	 *
8527 	 * Note: This is a critical sequence that needs to be maintained:
8528 	 *	1) Instantiate the kstats before any routines using the iopath
8529 	 *	   (i.e. sd_send_scsi_cmd).
8530 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8531 	 *	   stats (sd_set_pstats)here, following sd_validate_geometry(),
8532 	 *	   sd_register_devid(), and sd_cache_control().
8533 	 */
8534 	if (un->un_f_pkstats_enabled) {
8535 		sd_set_pstats(un);
8536 		SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8537 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8538 	}
8539 
8540 	sd_set_errstats(un);
8541 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8542 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8543 
8544 	/*
8545 	 * Find out what type of reservation this disk supports.
8546 	 */
8547 	switch (sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS, 0, NULL)) {
8548 	case 0:
8549 		/*
8550 		 * SCSI-3 reservations are supported.
8551 		 */
8552 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8553 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8554 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8555 		break;
8556 	case ENOTSUP:
8557 		/*
8558 		 * The PERSISTENT RESERVE IN command would not be recognized by
8559 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8560 		 */
8561 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8562 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8563 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8564 		break;
8565 	default:
8566 		/*
8567 		 * default to SCSI-3 reservations
8568 		 */
8569 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8570 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8571 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8572 		break;
8573 	}
8574 
8575 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8576 	    "sd_unit_attach: un:0x%p exit success\n", un);
8577 
8578 	return (DDI_SUCCESS);
8579 
8580 	/*
8581 	 * An error occurred during the attach; clean up & return failure.
8582 	 */
8583 
8584 devid_failed:
8585 
8586 setup_pm_failed:
8587 	ddi_remove_minor_node(devi, NULL);
8588 
8589 create_minor_nodes_failed:
8590 	/*
8591 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8592 	 */
8593 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8594 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8595 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8596 
8597 	if (un->un_f_is_fibre == FALSE) {
8598 	    (void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8599 	}
8600 
8601 spinup_failed:
8602 
8603 	mutex_enter(SD_MUTEX(un));
8604 
8605 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8606 	if (un->un_direct_priority_timeid != NULL) {
8607 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8608 		un->un_direct_priority_timeid = NULL;
8609 		mutex_exit(SD_MUTEX(un));
8610 		(void) untimeout(temp_id);
8611 		mutex_enter(SD_MUTEX(un));
8612 	}
8613 
8614 	/* Cancel any pending start/stop timeouts */
8615 	if (un->un_startstop_timeid != NULL) {
8616 		timeout_id_t temp_id = un->un_startstop_timeid;
8617 		un->un_startstop_timeid = NULL;
8618 		mutex_exit(SD_MUTEX(un));
8619 		(void) untimeout(temp_id);
8620 		mutex_enter(SD_MUTEX(un));
8621 	}
8622 
8623 	/* Cancel any pending reset-throttle timeouts */
8624 	if (un->un_reset_throttle_timeid != NULL) {
8625 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8626 		un->un_reset_throttle_timeid = NULL;
8627 		mutex_exit(SD_MUTEX(un));
8628 		(void) untimeout(temp_id);
8629 		mutex_enter(SD_MUTEX(un));
8630 	}
8631 
8632 	/* Cancel any pending retry timeouts */
8633 	if (un->un_retry_timeid != NULL) {
8634 		timeout_id_t temp_id = un->un_retry_timeid;
8635 		un->un_retry_timeid = NULL;
8636 		mutex_exit(SD_MUTEX(un));
8637 		(void) untimeout(temp_id);
8638 		mutex_enter(SD_MUTEX(un));
8639 	}
8640 
8641 	/* Cancel any pending delayed cv broadcast timeouts */
8642 	if (un->un_dcvb_timeid != NULL) {
8643 		timeout_id_t temp_id = un->un_dcvb_timeid;
8644 		un->un_dcvb_timeid = NULL;
8645 		mutex_exit(SD_MUTEX(un));
8646 		(void) untimeout(temp_id);
8647 		mutex_enter(SD_MUTEX(un));
8648 	}
8649 
8650 	mutex_exit(SD_MUTEX(un));
8651 
8652 	/* There should not be any in-progress I/O so ASSERT this check */
8653 	ASSERT(un->un_ncmds_in_transport == 0);
8654 	ASSERT(un->un_ncmds_in_driver == 0);
8655 
8656 	/* Do not free the softstate if the callback routine is active */
8657 	sd_sync_with_callback(un);
8658 
8659 	/*
8660 	 * Partition stats apparently are not used with removables. These would
8661 	 * not have been created during attach, so no need to clean them up...
8662 	 */
8663 	if (un->un_stats != NULL) {
8664 		kstat_delete(un->un_stats);
8665 		un->un_stats = NULL;
8666 	}
8667 	if (un->un_errstats != NULL) {
8668 		kstat_delete(un->un_errstats);
8669 		un->un_errstats = NULL;
8670 	}
8671 
8672 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8673 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8674 
8675 	ddi_prop_remove_all(devi);
8676 	sema_destroy(&un->un_semoclose);
8677 	cv_destroy(&un->un_state_cv);
8678 
8679 getrbuf_failed:
8680 
8681 	sd_free_rqs(un);
8682 
8683 alloc_rqs_failed:
8684 
8685 	devp->sd_private = NULL;
8686 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8687 
8688 get_softstate_failed:
8689 	/*
8690 	 * Note: the man pages are unclear as to whether or not doing a
8691 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8692 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8693 	 * ddi_get_soft_state() fails.  The implication seems to be
8694 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8695 	 */
8696 	ddi_soft_state_free(sd_state, instance);
8697 
8698 probe_failed:
8699 	scsi_unprobe(devp);
8700 #ifdef SDDEBUG
8701 	if ((sd_component_mask & SD_LOG_ATTACH_DETACH) &&
8702 	    (sd_level_mask & SD_LOGMASK_TRACE)) {
8703 		cmn_err(CE_CONT, "sd_unit_attach: un:0x%p exit failure\n",
8704 		    (void *)un);
8705 	}
8706 #endif
8707 	return (DDI_FAILURE);
8708 }
8709 
8710 
8711 /*
8712  *    Function: sd_unit_detach
8713  *
8714  * Description: Performs DDI_DETACH processing for sddetach().
8715  *
8716  * Return Code: DDI_SUCCESS
8717  *		DDI_FAILURE
8718  *
8719  *     Context: Kernel thread context
8720  */
8721 
8722 static int
8723 sd_unit_detach(dev_info_t *devi)
8724 {
8725 	struct scsi_device	*devp;
8726 	struct sd_lun		*un;
8727 	int			i;
8728 	dev_t			dev;
8729 	int			instance = ddi_get_instance(devi);
8730 
8731 	mutex_enter(&sd_detach_mutex);
8732 
8733 	/*
8734 	 * Fail the detach for any of the following:
8735 	 *  - Unable to get the sd_lun struct for the instance
8736 	 *  - A layered driver has an outstanding open on the instance
8737 	 *  - Another thread is already detaching this instance
8738 	 *  - Another thread is currently performing an open
8739 	 */
8740 	devp = ddi_get_driver_private(devi);
8741 	if ((devp == NULL) ||
8742 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8743 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
8744 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
8745 		mutex_exit(&sd_detach_mutex);
8746 		return (DDI_FAILURE);
8747 	}
8748 
8749 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8750 
8751 	/*
8752 	 * Mark this instance as currently in a detach, to inhibit any
8753 	 * opens from a layered driver.
8754 	 */
8755 	un->un_detach_count++;
8756 	mutex_exit(&sd_detach_mutex);
8757 
8758 	dev = sd_make_device(SD_DEVINFO(un));
8759 
8760 	_NOTE(COMPETING_THREADS_NOW);
8761 
8762 	mutex_enter(SD_MUTEX(un));
8763 
8764 	/*
8765 	 * Fail the detach if there are any outstanding layered
8766 	 * opens on this device.
8767 	 */
8768 	for (i = 0; i < NDKMAP; i++) {
8769 		if (un->un_ocmap.lyropen[i] != 0) {
8770 			goto err_notclosed;
8771 		}
8772 	}
8773 
8774 	/*
8775 	 * Verify there are NO outstanding commands issued to this device.
8776 	 * ie, un_ncmds_in_transport == 0.
8777 	 * It's possible to have outstanding commands through the physio
8778 	 * code path, even though everything's closed.
8779 	 */
8780 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8781 	    (un->un_direct_priority_timeid != NULL) ||
8782 	    (un->un_state == SD_STATE_RWAIT)) {
8783 		mutex_exit(SD_MUTEX(un));
8784 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8785 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8786 		goto err_stillbusy;
8787 	}
8788 
8789 	/*
8790 	 * If we have the device reserved, release the reservation.
8791 	 */
8792 	if ((un->un_resvd_status & SD_RESERVE) &&
8793 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8794 		mutex_exit(SD_MUTEX(un));
8795 		/*
8796 		 * Note: sd_reserve_release sends a command to the device
8797 		 * via the sd_ioctlcmd() path, and can sleep.
8798 		 */
8799 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8800 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8801 			    "sd_dr_detach: Cannot release reservation \n");
8802 		}
8803 	} else {
8804 		mutex_exit(SD_MUTEX(un));
8805 	}
8806 
8807 	/*
8808 	 * Untimeout any reserve recover, throttle reset, restart unit
8809 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8810 	 * from getting nulled by their callback functions.
8811 	 */
8812 	mutex_enter(SD_MUTEX(un));
8813 	if (un->un_resvd_timeid != NULL) {
8814 		timeout_id_t temp_id = un->un_resvd_timeid;
8815 		un->un_resvd_timeid = NULL;
8816 		mutex_exit(SD_MUTEX(un));
8817 		(void) untimeout(temp_id);
8818 		mutex_enter(SD_MUTEX(un));
8819 	}
8820 
8821 	if (un->un_reset_throttle_timeid != NULL) {
8822 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8823 		un->un_reset_throttle_timeid = NULL;
8824 		mutex_exit(SD_MUTEX(un));
8825 		(void) untimeout(temp_id);
8826 		mutex_enter(SD_MUTEX(un));
8827 	}
8828 
8829 	if (un->un_startstop_timeid != NULL) {
8830 		timeout_id_t temp_id = un->un_startstop_timeid;
8831 		un->un_startstop_timeid = NULL;
8832 		mutex_exit(SD_MUTEX(un));
8833 		(void) untimeout(temp_id);
8834 		mutex_enter(SD_MUTEX(un));
8835 	}
8836 
8837 	if (un->un_dcvb_timeid != NULL) {
8838 		timeout_id_t temp_id = un->un_dcvb_timeid;
8839 		un->un_dcvb_timeid = NULL;
8840 		mutex_exit(SD_MUTEX(un));
8841 		(void) untimeout(temp_id);
8842 	} else {
8843 		mutex_exit(SD_MUTEX(un));
8844 	}
8845 
8846 	/* Remove any pending reservation reclaim requests for this device */
8847 	sd_rmv_resv_reclaim_req(dev);
8848 
8849 	mutex_enter(SD_MUTEX(un));
8850 
8851 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8852 	if (un->un_direct_priority_timeid != NULL) {
8853 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8854 		un->un_direct_priority_timeid = NULL;
8855 		mutex_exit(SD_MUTEX(un));
8856 		(void) untimeout(temp_id);
8857 		mutex_enter(SD_MUTEX(un));
8858 	}
8859 
8860 	/* Cancel any active multi-host disk watch thread requests */
8861 	if (un->un_mhd_token != NULL) {
8862 		mutex_exit(SD_MUTEX(un));
8863 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8864 		if (scsi_watch_request_terminate(un->un_mhd_token,
8865 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8866 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8867 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8868 			/*
8869 			 * Note: We are returning here after having removed
8870 			 * some driver timeouts above. This is consistent with
8871 			 * the legacy implementation but perhaps the watch
8872 			 * terminate call should be made with the wait flag set.
8873 			 */
8874 			goto err_stillbusy;
8875 		}
8876 		mutex_enter(SD_MUTEX(un));
8877 		un->un_mhd_token = NULL;
8878 	}
8879 
8880 	if (un->un_swr_token != NULL) {
8881 		mutex_exit(SD_MUTEX(un));
8882 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8883 		if (scsi_watch_request_terminate(un->un_swr_token,
8884 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8885 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8886 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8887 			/*
8888 			 * Note: We are returning here after having removed
8889 			 * some driver timeouts above. This is consistent with
8890 			 * the legacy implementation but perhaps the watch
8891 			 * terminate call should be made with the wait flag set.
8892 			 */
8893 			goto err_stillbusy;
8894 		}
8895 		mutex_enter(SD_MUTEX(un));
8896 		un->un_swr_token = NULL;
8897 	}
8898 
8899 	mutex_exit(SD_MUTEX(un));
8900 
8901 	/*
8902 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8903 	 * if we have not registered one.
8904 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8905 	 */
8906 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8907 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8908 
8909 	/*
8910 	 * protect the timeout pointers from getting nulled by
8911 	 * their callback functions during the cancellation process.
8912 	 * In such a scenario untimeout can be invoked with a null value.
8913 	 */
8914 	_NOTE(NO_COMPETING_THREADS_NOW);
8915 
8916 	mutex_enter(&un->un_pm_mutex);
8917 	if (un->un_pm_idle_timeid != NULL) {
8918 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8919 		un->un_pm_idle_timeid = NULL;
8920 		mutex_exit(&un->un_pm_mutex);
8921 
8922 		/*
8923 		 * Timeout is active; cancel it.
8924 		 * Note that it'll never be active on a device
8925 		 * that does not support PM therefore we don't
8926 		 * have to check before calling pm_idle_component.
8927 		 */
8928 		(void) untimeout(temp_id);
8929 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8930 		mutex_enter(&un->un_pm_mutex);
8931 	}
8932 
8933 	/*
8934 	 * Check whether there is already a timeout scheduled for power
8935 	 * management. If yes then don't lower the power here, that's.
8936 	 * the timeout handler's job.
8937 	 */
8938 	if (un->un_pm_timeid != NULL) {
8939 		timeout_id_t temp_id = un->un_pm_timeid;
8940 		un->un_pm_timeid = NULL;
8941 		mutex_exit(&un->un_pm_mutex);
8942 		/*
8943 		 * Timeout is active; cancel it.
8944 		 * Note that it'll never be active on a device
8945 		 * that does not support PM therefore we don't
8946 		 * have to check before calling pm_idle_component.
8947 		 */
8948 		(void) untimeout(temp_id);
8949 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8950 
8951 	} else {
8952 		mutex_exit(&un->un_pm_mutex);
8953 		if ((un->un_f_pm_is_enabled == TRUE) &&
8954 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
8955 		    DDI_SUCCESS)) {
8956 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8957 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8958 			/*
8959 			 * Fix for bug: 4297749, item # 13
8960 			 * The above test now includes a check to see if PM is
8961 			 * supported by this device before call
8962 			 * pm_lower_power().
8963 			 * Note, the following is not dead code. The call to
8964 			 * pm_lower_power above will generate a call back into
8965 			 * our sdpower routine which might result in a timeout
8966 			 * handler getting activated. Therefore the following
8967 			 * code is valid and necessary.
8968 			 */
8969 			mutex_enter(&un->un_pm_mutex);
8970 			if (un->un_pm_timeid != NULL) {
8971 				timeout_id_t temp_id = un->un_pm_timeid;
8972 				un->un_pm_timeid = NULL;
8973 				mutex_exit(&un->un_pm_mutex);
8974 				(void) untimeout(temp_id);
8975 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8976 			} else {
8977 				mutex_exit(&un->un_pm_mutex);
8978 			}
8979 		}
8980 	}
8981 
8982 	/*
8983 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8984 	 * Relocated here from above to be after the call to
8985 	 * pm_lower_power, which was getting errors.
8986 	 */
8987 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8988 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8989 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8990 
8991 	if (un->un_f_is_fibre == FALSE) {
8992 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8993 	}
8994 
8995 	/*
8996 	 * Remove any event callbacks, fibre only
8997 	 */
8998 	if (un->un_f_is_fibre == TRUE) {
8999 		if ((un->un_insert_event != NULL) &&
9000 			(ddi_remove_event_handler(un->un_insert_cb_id) !=
9001 				DDI_SUCCESS)) {
9002 			/*
9003 			 * Note: We are returning here after having done
9004 			 * substantial cleanup above. This is consistent
9005 			 * with the legacy implementation but this may not
9006 			 * be the right thing to do.
9007 			 */
9008 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9009 				"sd_dr_detach: Cannot cancel insert event\n");
9010 			goto err_remove_event;
9011 		}
9012 		un->un_insert_event = NULL;
9013 
9014 		if ((un->un_remove_event != NULL) &&
9015 			(ddi_remove_event_handler(un->un_remove_cb_id) !=
9016 				DDI_SUCCESS)) {
9017 			/*
9018 			 * Note: We are returning here after having done
9019 			 * substantial cleanup above. This is consistent
9020 			 * with the legacy implementation but this may not
9021 			 * be the right thing to do.
9022 			 */
9023 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9024 				"sd_dr_detach: Cannot cancel remove event\n");
9025 			goto err_remove_event;
9026 		}
9027 		un->un_remove_event = NULL;
9028 	}
9029 
9030 	/* Do not free the softstate if the callback routine is active */
9031 	sd_sync_with_callback(un);
9032 
9033 	/*
9034 	 * Hold the detach mutex here, to make sure that no other threads ever
9035 	 * can access a (partially) freed soft state structure.
9036 	 */
9037 	mutex_enter(&sd_detach_mutex);
9038 
9039 	/*
9040 	 * Clean up the soft state struct.
9041 	 * Cleanup is done in reverse order of allocs/inits.
9042 	 * At this point there should be no competing threads anymore.
9043 	 */
9044 
9045 	/* Unregister and free device id. */
9046 	ddi_devid_unregister(devi);
9047 	if (un->un_devid) {
9048 		ddi_devid_free(un->un_devid);
9049 		un->un_devid = NULL;
9050 	}
9051 
9052 	/*
9053 	 * Destroy wmap cache if it exists.
9054 	 */
9055 	if (un->un_wm_cache != NULL) {
9056 		kmem_cache_destroy(un->un_wm_cache);
9057 		un->un_wm_cache = NULL;
9058 	}
9059 
9060 	/* Remove minor nodes */
9061 	ddi_remove_minor_node(devi, NULL);
9062 
9063 	/*
9064 	 * kstat cleanup is done in detach for all device types (4363169).
9065 	 * We do not want to fail detach if the device kstats are not deleted
9066 	 * since there is a confusion about the devo_refcnt for the device.
9067 	 * We just delete the kstats and let detach complete successfully.
9068 	 */
9069 	if (un->un_stats != NULL) {
9070 		kstat_delete(un->un_stats);
9071 		un->un_stats = NULL;
9072 	}
9073 	if (un->un_errstats != NULL) {
9074 		kstat_delete(un->un_errstats);
9075 		un->un_errstats = NULL;
9076 	}
9077 
9078 	/* Remove partition stats */
9079 	if (un->un_f_pkstats_enabled) {
9080 		for (i = 0; i < NSDMAP; i++) {
9081 			if (un->un_pstats[i] != NULL) {
9082 				kstat_delete(un->un_pstats[i]);
9083 				un->un_pstats[i] = NULL;
9084 			}
9085 		}
9086 	}
9087 
9088 	/* Remove xbuf registration */
9089 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
9090 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
9091 
9092 	/* Remove driver properties */
9093 	ddi_prop_remove_all(devi);
9094 
9095 	mutex_destroy(&un->un_pm_mutex);
9096 	cv_destroy(&un->un_pm_busy_cv);
9097 
9098 	cv_destroy(&un->un_wcc_cv);
9099 
9100 	/* Open/close semaphore */
9101 	sema_destroy(&un->un_semoclose);
9102 
9103 	/* Removable media condvar. */
9104 	cv_destroy(&un->un_state_cv);
9105 
9106 	/* Suspend/resume condvar. */
9107 	cv_destroy(&un->un_suspend_cv);
9108 	cv_destroy(&un->un_disk_busy_cv);
9109 
9110 	sd_free_rqs(un);
9111 
9112 	/* Free up soft state */
9113 	devp->sd_private = NULL;
9114 	bzero(un, sizeof (struct sd_lun));
9115 	ddi_soft_state_free(sd_state, instance);
9116 
9117 	mutex_exit(&sd_detach_mutex);
9118 
9119 	/* This frees up the INQUIRY data associated with the device. */
9120 	scsi_unprobe(devp);
9121 
9122 	return (DDI_SUCCESS);
9123 
9124 err_notclosed:
9125 	mutex_exit(SD_MUTEX(un));
9126 
9127 err_stillbusy:
9128 	_NOTE(NO_COMPETING_THREADS_NOW);
9129 
9130 err_remove_event:
9131 	mutex_enter(&sd_detach_mutex);
9132 	un->un_detach_count--;
9133 	mutex_exit(&sd_detach_mutex);
9134 
9135 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
9136 	return (DDI_FAILURE);
9137 }
9138 
9139 
9140 /*
9141  * Driver minor node structure and data table
9142  */
9143 struct driver_minor_data {
9144 	char	*name;
9145 	minor_t	minor;
9146 	int	type;
9147 };
9148 
9149 static struct driver_minor_data sd_minor_data[] = {
9150 	{"a", 0, S_IFBLK},
9151 	{"b", 1, S_IFBLK},
9152 	{"c", 2, S_IFBLK},
9153 	{"d", 3, S_IFBLK},
9154 	{"e", 4, S_IFBLK},
9155 	{"f", 5, S_IFBLK},
9156 	{"g", 6, S_IFBLK},
9157 	{"h", 7, S_IFBLK},
9158 #if defined(_SUNOS_VTOC_16)
9159 	{"i", 8, S_IFBLK},
9160 	{"j", 9, S_IFBLK},
9161 	{"k", 10, S_IFBLK},
9162 	{"l", 11, S_IFBLK},
9163 	{"m", 12, S_IFBLK},
9164 	{"n", 13, S_IFBLK},
9165 	{"o", 14, S_IFBLK},
9166 	{"p", 15, S_IFBLK},
9167 #endif			/* defined(_SUNOS_VTOC_16) */
9168 #if defined(_FIRMWARE_NEEDS_FDISK)
9169 	{"q", 16, S_IFBLK},
9170 	{"r", 17, S_IFBLK},
9171 	{"s", 18, S_IFBLK},
9172 	{"t", 19, S_IFBLK},
9173 	{"u", 20, S_IFBLK},
9174 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
9175 	{"a,raw", 0, S_IFCHR},
9176 	{"b,raw", 1, S_IFCHR},
9177 	{"c,raw", 2, S_IFCHR},
9178 	{"d,raw", 3, S_IFCHR},
9179 	{"e,raw", 4, S_IFCHR},
9180 	{"f,raw", 5, S_IFCHR},
9181 	{"g,raw", 6, S_IFCHR},
9182 	{"h,raw", 7, S_IFCHR},
9183 #if defined(_SUNOS_VTOC_16)
9184 	{"i,raw", 8, S_IFCHR},
9185 	{"j,raw", 9, S_IFCHR},
9186 	{"k,raw", 10, S_IFCHR},
9187 	{"l,raw", 11, S_IFCHR},
9188 	{"m,raw", 12, S_IFCHR},
9189 	{"n,raw", 13, S_IFCHR},
9190 	{"o,raw", 14, S_IFCHR},
9191 	{"p,raw", 15, S_IFCHR},
9192 #endif			/* defined(_SUNOS_VTOC_16) */
9193 #if defined(_FIRMWARE_NEEDS_FDISK)
9194 	{"q,raw", 16, S_IFCHR},
9195 	{"r,raw", 17, S_IFCHR},
9196 	{"s,raw", 18, S_IFCHR},
9197 	{"t,raw", 19, S_IFCHR},
9198 	{"u,raw", 20, S_IFCHR},
9199 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
9200 	{0}
9201 };
9202 
9203 static struct driver_minor_data sd_minor_data_efi[] = {
9204 	{"a", 0, S_IFBLK},
9205 	{"b", 1, S_IFBLK},
9206 	{"c", 2, S_IFBLK},
9207 	{"d", 3, S_IFBLK},
9208 	{"e", 4, S_IFBLK},
9209 	{"f", 5, S_IFBLK},
9210 	{"g", 6, S_IFBLK},
9211 	{"wd", 7, S_IFBLK},
9212 #if defined(_FIRMWARE_NEEDS_FDISK)
9213 	{"q", 16, S_IFBLK},
9214 	{"r", 17, S_IFBLK},
9215 	{"s", 18, S_IFBLK},
9216 	{"t", 19, S_IFBLK},
9217 	{"u", 20, S_IFBLK},
9218 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
9219 	{"a,raw", 0, S_IFCHR},
9220 	{"b,raw", 1, S_IFCHR},
9221 	{"c,raw", 2, S_IFCHR},
9222 	{"d,raw", 3, S_IFCHR},
9223 	{"e,raw", 4, S_IFCHR},
9224 	{"f,raw", 5, S_IFCHR},
9225 	{"g,raw", 6, S_IFCHR},
9226 	{"wd,raw", 7, S_IFCHR},
9227 #if defined(_FIRMWARE_NEEDS_FDISK)
9228 	{"q,raw", 16, S_IFCHR},
9229 	{"r,raw", 17, S_IFCHR},
9230 	{"s,raw", 18, S_IFCHR},
9231 	{"t,raw", 19, S_IFCHR},
9232 	{"u,raw", 20, S_IFCHR},
9233 #endif			/* defined(_FIRMWARE_NEEDS_FDISK) */
9234 	{0}
9235 };
9236 
9237 
9238 /*
9239  *    Function: sd_create_minor_nodes
9240  *
9241  * Description: Create the minor device nodes for the instance.
9242  *
9243  *   Arguments: un - driver soft state (unit) structure
9244  *		devi - pointer to device info structure
9245  *
9246  * Return Code: DDI_SUCCESS
9247  *		DDI_FAILURE
9248  *
9249  *     Context: Kernel thread context
9250  */
9251 
9252 static int
9253 sd_create_minor_nodes(struct sd_lun *un, dev_info_t *devi)
9254 {
9255 	struct driver_minor_data	*dmdp;
9256 	struct scsi_device		*devp;
9257 	int				instance;
9258 	char				name[48];
9259 
9260 	ASSERT(un != NULL);
9261 	devp = ddi_get_driver_private(devi);
9262 	instance = ddi_get_instance(devp->sd_dev);
9263 
9264 	/*
9265 	 * Create all the minor nodes for this target.
9266 	 */
9267 	if (un->un_blockcount > DK_MAX_BLOCKS)
9268 		dmdp = sd_minor_data_efi;
9269 	else
9270 		dmdp = sd_minor_data;
9271 	while (dmdp->name != NULL) {
9272 
9273 		(void) sprintf(name, "%s", dmdp->name);
9274 
9275 		if (ddi_create_minor_node(devi, name, dmdp->type,
9276 		    (instance << SDUNIT_SHIFT) | dmdp->minor,
9277 		    un->un_node_type, NULL) == DDI_FAILURE) {
9278 			/*
9279 			 * Clean up any nodes that may have been created, in
9280 			 * case this fails in the middle of the loop.
9281 			 */
9282 			ddi_remove_minor_node(devi, NULL);
9283 			return (DDI_FAILURE);
9284 		}
9285 		dmdp++;
9286 	}
9287 
9288 	return (DDI_SUCCESS);
9289 }
9290 
9291 
9292 /*
9293  *    Function: sd_create_errstats
9294  *
9295  * Description: This routine instantiates the device error stats.
9296  *
9297  *		Note: During attach the stats are instantiated first so they are
9298  *		available for attach-time routines that utilize the driver
9299  *		iopath to send commands to the device. The stats are initialized
9300  *		separately so data obtained during some attach-time routines is
9301  *		available. (4362483)
9302  *
9303  *   Arguments: un - driver soft state (unit) structure
9304  *		instance - driver instance
9305  *
9306  *     Context: Kernel thread context
9307  */
9308 
9309 static void
9310 sd_create_errstats(struct sd_lun *un, int instance)
9311 {
9312 	struct	sd_errstats	*stp;
9313 	char	kstatmodule_err[KSTAT_STRLEN];
9314 	char	kstatname[KSTAT_STRLEN];
9315 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
9316 
9317 	ASSERT(un != NULL);
9318 
9319 	if (un->un_errstats != NULL) {
9320 		return;
9321 	}
9322 
9323 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
9324 	    "%serr", sd_label);
9325 	(void) snprintf(kstatname, sizeof (kstatname),
9326 	    "%s%d,err", sd_label, instance);
9327 
9328 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
9329 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
9330 
9331 	if (un->un_errstats == NULL) {
9332 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9333 		    "sd_create_errstats: Failed kstat_create\n");
9334 		return;
9335 	}
9336 
9337 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9338 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
9339 	    KSTAT_DATA_UINT32);
9340 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
9341 	    KSTAT_DATA_UINT32);
9342 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
9343 	    KSTAT_DATA_UINT32);
9344 	kstat_named_init(&stp->sd_vid,		"Vendor",
9345 	    KSTAT_DATA_CHAR);
9346 	kstat_named_init(&stp->sd_pid,		"Product",
9347 	    KSTAT_DATA_CHAR);
9348 	kstat_named_init(&stp->sd_revision,	"Revision",
9349 	    KSTAT_DATA_CHAR);
9350 	kstat_named_init(&stp->sd_serial,	"Serial No",
9351 	    KSTAT_DATA_CHAR);
9352 	kstat_named_init(&stp->sd_capacity,	"Size",
9353 	    KSTAT_DATA_ULONGLONG);
9354 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
9355 	    KSTAT_DATA_UINT32);
9356 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
9357 	    KSTAT_DATA_UINT32);
9358 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
9359 	    KSTAT_DATA_UINT32);
9360 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9361 	    KSTAT_DATA_UINT32);
9362 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9363 	    KSTAT_DATA_UINT32);
9364 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9365 	    KSTAT_DATA_UINT32);
9366 
9367 	un->un_errstats->ks_private = un;
9368 	un->un_errstats->ks_update  = nulldev;
9369 
9370 	kstat_install(un->un_errstats);
9371 }
9372 
9373 
9374 /*
9375  *    Function: sd_set_errstats
9376  *
9377  * Description: This routine sets the value of the vendor id, product id,
9378  *		revision, serial number, and capacity device error stats.
9379  *
9380  *		Note: During attach the stats are instantiated first so they are
9381  *		available for attach-time routines that utilize the driver
9382  *		iopath to send commands to the device. The stats are initialized
9383  *		separately so data obtained during some attach-time routines is
9384  *		available. (4362483)
9385  *
9386  *   Arguments: un - driver soft state (unit) structure
9387  *
9388  *     Context: Kernel thread context
9389  */
9390 
9391 static void
9392 sd_set_errstats(struct sd_lun *un)
9393 {
9394 	struct	sd_errstats	*stp;
9395 
9396 	ASSERT(un != NULL);
9397 	ASSERT(un->un_errstats != NULL);
9398 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9399 	ASSERT(stp != NULL);
9400 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9401 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9402 	(void) strncpy(stp->sd_revision.value.c,
9403 	    un->un_sd->sd_inq->inq_revision, 4);
9404 
9405 	/*
9406 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9407 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9408 	 * (4376302))
9409 	 */
9410 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9411 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9412 		    sizeof (SD_INQUIRY(un)->inq_serial));
9413 	}
9414 
9415 	if (un->un_f_blockcount_is_valid != TRUE) {
9416 		/*
9417 		 * Set capacity error stat to 0 for no media. This ensures
9418 		 * a valid capacity is displayed in response to 'iostat -E'
9419 		 * when no media is present in the device.
9420 		 */
9421 		stp->sd_capacity.value.ui64 = 0;
9422 	} else {
9423 		/*
9424 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9425 		 * capacity.
9426 		 *
9427 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9428 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9429 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9430 		 */
9431 		stp->sd_capacity.value.ui64 = (uint64_t)
9432 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9433 	}
9434 }
9435 
9436 
9437 /*
9438  *    Function: sd_set_pstats
9439  *
9440  * Description: This routine instantiates and initializes the partition
9441  *              stats for each partition with more than zero blocks.
9442  *		(4363169)
9443  *
9444  *   Arguments: un - driver soft state (unit) structure
9445  *
9446  *     Context: Kernel thread context
9447  */
9448 
9449 static void
9450 sd_set_pstats(struct sd_lun *un)
9451 {
9452 	char	kstatname[KSTAT_STRLEN];
9453 	int	instance;
9454 	int	i;
9455 
9456 	ASSERT(un != NULL);
9457 
9458 	instance = ddi_get_instance(SD_DEVINFO(un));
9459 
9460 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9461 	for (i = 0; i < NSDMAP; i++) {
9462 		if ((un->un_pstats[i] == NULL) &&
9463 		    (un->un_map[i].dkl_nblk != 0)) {
9464 			(void) snprintf(kstatname, sizeof (kstatname),
9465 			    "%s%d,%s", sd_label, instance,
9466 			    sd_minor_data[i].name);
9467 			un->un_pstats[i] = kstat_create(sd_label,
9468 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9469 			    1, KSTAT_FLAG_PERSISTENT);
9470 			if (un->un_pstats[i] != NULL) {
9471 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9472 				kstat_install(un->un_pstats[i]);
9473 			}
9474 		}
9475 	}
9476 }
9477 
9478 
9479 #if (defined(__fibre))
9480 /*
9481  *    Function: sd_init_event_callbacks
9482  *
9483  * Description: This routine initializes the insertion and removal event
9484  *		callbacks. (fibre only)
9485  *
9486  *   Arguments: un - driver soft state (unit) structure
9487  *
9488  *     Context: Kernel thread context
9489  */
9490 
9491 static void
9492 sd_init_event_callbacks(struct sd_lun *un)
9493 {
9494 	ASSERT(un != NULL);
9495 
9496 	if ((un->un_insert_event == NULL) &&
9497 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9498 	    &un->un_insert_event) == DDI_SUCCESS)) {
9499 		/*
9500 		 * Add the callback for an insertion event
9501 		 */
9502 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9503 		    un->un_insert_event, sd_event_callback, (void *)un,
9504 		    &(un->un_insert_cb_id));
9505 	}
9506 
9507 	if ((un->un_remove_event == NULL) &&
9508 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9509 	    &un->un_remove_event) == DDI_SUCCESS)) {
9510 		/*
9511 		 * Add the callback for a removal event
9512 		 */
9513 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9514 		    un->un_remove_event, sd_event_callback, (void *)un,
9515 		    &(un->un_remove_cb_id));
9516 	}
9517 }
9518 
9519 
9520 /*
9521  *    Function: sd_event_callback
9522  *
9523  * Description: This routine handles insert/remove events (photon). The
9524  *		state is changed to OFFLINE which can be used to supress
9525  *		error msgs. (fibre only)
9526  *
9527  *   Arguments: un - driver soft state (unit) structure
9528  *
9529  *     Context: Callout thread context
9530  */
9531 /* ARGSUSED */
9532 static void
9533 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9534     void *bus_impldata)
9535 {
9536 	struct sd_lun *un = (struct sd_lun *)arg;
9537 
9538 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9539 	if (event == un->un_insert_event) {
9540 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9541 		mutex_enter(SD_MUTEX(un));
9542 		if (un->un_state == SD_STATE_OFFLINE) {
9543 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9544 				un->un_state = un->un_last_state;
9545 			} else {
9546 				/*
9547 				 * We have gone through SUSPEND/RESUME while
9548 				 * we were offline. Restore the last state
9549 				 */
9550 				un->un_state = un->un_save_state;
9551 			}
9552 		}
9553 		mutex_exit(SD_MUTEX(un));
9554 
9555 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9556 	} else if (event == un->un_remove_event) {
9557 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9558 		mutex_enter(SD_MUTEX(un));
9559 		/*
9560 		 * We need to handle an event callback that occurs during
9561 		 * the suspend operation, since we don't prevent it.
9562 		 */
9563 		if (un->un_state != SD_STATE_OFFLINE) {
9564 			if (un->un_state != SD_STATE_SUSPENDED) {
9565 				New_state(un, SD_STATE_OFFLINE);
9566 			} else {
9567 				un->un_last_state = SD_STATE_OFFLINE;
9568 			}
9569 		}
9570 		mutex_exit(SD_MUTEX(un));
9571 	} else {
9572 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9573 		    "!Unknown event\n");
9574 	}
9575 
9576 }
9577 #endif
9578 
9579 /*
9580  *    Function: sd_cache_control()
9581  *
9582  * Description: This routine is the driver entry point for setting
9583  *		read and write caching by modifying the WCE (write cache
9584  *		enable) and RCD (read cache disable) bits of mode
9585  *		page 8 (MODEPAGE_CACHING).
9586  *
9587  *   Arguments: un - driver soft state (unit) structure
9588  *		rcd_flag - flag for controlling the read cache
9589  *		wce_flag - flag for controlling the write cache
9590  *
9591  * Return Code: EIO
9592  *		code returned by sd_send_scsi_MODE_SENSE and
9593  *		sd_send_scsi_MODE_SELECT
9594  *
9595  *     Context: Kernel Thread
9596  */
9597 
9598 static int
9599 sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag)
9600 {
9601 	struct mode_caching	*mode_caching_page;
9602 	uchar_t			*header;
9603 	size_t			buflen;
9604 	int			hdrlen;
9605 	int			bd_len;
9606 	int			rval = 0;
9607 	struct mode_header_grp2	*mhp;
9608 
9609 	ASSERT(un != NULL);
9610 
9611 	/*
9612 	 * Do a test unit ready, otherwise a mode sense may not work if this
9613 	 * is the first command sent to the device after boot.
9614 	 */
9615 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9616 
9617 	if (un->un_f_cfg_is_atapi == TRUE) {
9618 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9619 	} else {
9620 		hdrlen = MODE_HEADER_LENGTH;
9621 	}
9622 
9623 	/*
9624 	 * Allocate memory for the retrieved mode page and its headers.  Set
9625 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
9626 	 * we get all of the mode sense data otherwise, the mode select
9627 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
9628 	 */
9629 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
9630 		sizeof (struct mode_cache_scsi3);
9631 
9632 	header = kmem_zalloc(buflen, KM_SLEEP);
9633 
9634 	/* Get the information from the device. */
9635 	if (un->un_f_cfg_is_atapi == TRUE) {
9636 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
9637 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9638 	} else {
9639 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
9640 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9641 	}
9642 	if (rval != 0) {
9643 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9644 		    "sd_cache_control: Mode Sense Failed\n");
9645 		kmem_free(header, buflen);
9646 		return (rval);
9647 	}
9648 
9649 	/*
9650 	 * Determine size of Block Descriptors in order to locate
9651 	 * the mode page data. ATAPI devices return 0, SCSI devices
9652 	 * should return MODE_BLK_DESC_LENGTH.
9653 	 */
9654 	if (un->un_f_cfg_is_atapi == TRUE) {
9655 		mhp	= (struct mode_header_grp2 *)header;
9656 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9657 	} else {
9658 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9659 	}
9660 
9661 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9662 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9663 		    "sd_cache_control: Mode Sense returned invalid "
9664 		    "block descriptor length\n");
9665 		kmem_free(header, buflen);
9666 		return (EIO);
9667 	}
9668 
9669 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9670 
9671 	/* Check the relevant bits on successful mode sense. */
9672 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9673 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9674 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9675 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9676 
9677 		size_t sbuflen;
9678 
9679 		/*
9680 		 * Construct select buffer length based on the
9681 		 * length of the sense data returned.
9682 		 */
9683 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
9684 				sizeof (struct mode_page) +
9685 				(int)mode_caching_page->mode_page.length;
9686 
9687 		/*
9688 		 * Set the caching bits as requested.
9689 		 */
9690 		if (rcd_flag == SD_CACHE_ENABLE)
9691 			mode_caching_page->rcd = 0;
9692 		else if (rcd_flag == SD_CACHE_DISABLE)
9693 			mode_caching_page->rcd = 1;
9694 
9695 		if (wce_flag == SD_CACHE_ENABLE)
9696 			mode_caching_page->wce = 1;
9697 		else if (wce_flag == SD_CACHE_DISABLE)
9698 			mode_caching_page->wce = 0;
9699 
9700 		/* Clear reserved bits before mode select. */
9701 		mode_caching_page->mode_page.ps = 0;
9702 
9703 		/*
9704 		 * Clear out mode header for mode select.
9705 		 * The rest of the retrieved page will be reused.
9706 		 */
9707 		bzero(header, hdrlen);
9708 
9709 		if (un->un_f_cfg_is_atapi == TRUE) {
9710 			mhp = (struct mode_header_grp2 *)header;
9711 			mhp->bdesc_length_hi = bd_len >> 8;
9712 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
9713 		} else {
9714 			((struct mode_header *)header)->bdesc_length = bd_len;
9715 		}
9716 
9717 		/* Issue mode select to change the cache settings */
9718 		if (un->un_f_cfg_is_atapi == TRUE) {
9719 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, header,
9720 			    sbuflen, SD_SAVE_PAGE, SD_PATH_DIRECT);
9721 		} else {
9722 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
9723 			    sbuflen, SD_SAVE_PAGE, SD_PATH_DIRECT);
9724 		}
9725 	}
9726 
9727 	kmem_free(header, buflen);
9728 	return (rval);
9729 }
9730 
9731 
9732 /*
9733  *    Function: sd_get_write_cache_enabled()
9734  *
9735  * Description: This routine is the driver entry point for determining if
9736  *		write caching is enabled.  It examines the WCE (write cache
9737  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
9738  *
9739  *   Arguments: un - driver soft state (unit) structure
9740  *   		is_enabled - pointer to int where write cache enabled state
9741  *   			is returned (non-zero -> write cache enabled)
9742  *
9743  *
9744  * Return Code: EIO
9745  *		code returned by sd_send_scsi_MODE_SENSE
9746  *
9747  *     Context: Kernel Thread
9748  *
9749  * NOTE: If ioctl is added to disable write cache, this sequence should
9750  * be followed so that no locking is required for accesses to
9751  * un->un_f_write_cache_enabled:
9752  * 	do mode select to clear wce
9753  * 	do synchronize cache to flush cache
9754  * 	set un->un_f_write_cache_enabled = FALSE
9755  *
9756  * Conversely, an ioctl to enable the write cache should be done
9757  * in this order:
9758  * 	set un->un_f_write_cache_enabled = TRUE
9759  * 	do mode select to set wce
9760  */
9761 
9762 static int
9763 sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled)
9764 {
9765 	struct mode_caching	*mode_caching_page;
9766 	uchar_t			*header;
9767 	size_t			buflen;
9768 	int			hdrlen;
9769 	int			bd_len;
9770 	int			rval = 0;
9771 
9772 	ASSERT(un != NULL);
9773 	ASSERT(is_enabled != NULL);
9774 
9775 	/* in case of error, flag as enabled */
9776 	*is_enabled = TRUE;
9777 
9778 	/*
9779 	 * Do a test unit ready, otherwise a mode sense may not work if this
9780 	 * is the first command sent to the device after boot.
9781 	 */
9782 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9783 
9784 	if (un->un_f_cfg_is_atapi == TRUE) {
9785 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9786 	} else {
9787 		hdrlen = MODE_HEADER_LENGTH;
9788 	}
9789 
9790 	/*
9791 	 * Allocate memory for the retrieved mode page and its headers.  Set
9792 	 * a pointer to the page itself.
9793 	 */
9794 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
9795 	header = kmem_zalloc(buflen, KM_SLEEP);
9796 
9797 	/* Get the information from the device. */
9798 	if (un->un_f_cfg_is_atapi == TRUE) {
9799 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
9800 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9801 	} else {
9802 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
9803 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9804 	}
9805 	if (rval != 0) {
9806 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9807 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
9808 		kmem_free(header, buflen);
9809 		return (rval);
9810 	}
9811 
9812 	/*
9813 	 * Determine size of Block Descriptors in order to locate
9814 	 * the mode page data. ATAPI devices return 0, SCSI devices
9815 	 * should return MODE_BLK_DESC_LENGTH.
9816 	 */
9817 	if (un->un_f_cfg_is_atapi == TRUE) {
9818 		struct mode_header_grp2	*mhp;
9819 		mhp	= (struct mode_header_grp2 *)header;
9820 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9821 	} else {
9822 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9823 	}
9824 
9825 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9826 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9827 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
9828 		    "block descriptor length\n");
9829 		kmem_free(header, buflen);
9830 		return (EIO);
9831 	}
9832 
9833 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9834 	*is_enabled = mode_caching_page->wce;
9835 
9836 	kmem_free(header, buflen);
9837 	return (0);
9838 }
9839 
9840 
9841 /*
9842  *    Function: sd_make_device
9843  *
9844  * Description: Utility routine to return the Solaris device number from
9845  *		the data in the device's dev_info structure.
9846  *
9847  * Return Code: The Solaris device number
9848  *
9849  *     Context: Any
9850  */
9851 
9852 static dev_t
9853 sd_make_device(dev_info_t *devi)
9854 {
9855 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
9856 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9857 }
9858 
9859 
9860 /*
9861  *    Function: sd_pm_entry
9862  *
9863  * Description: Called at the start of a new command to manage power
9864  *		and busy status of a device. This includes determining whether
9865  *		the current power state of the device is sufficient for
9866  *		performing the command or whether it must be changed.
9867  *		The PM framework is notified appropriately.
9868  *		Only with a return status of DDI_SUCCESS will the
9869  *		component be busy to the framework.
9870  *
9871  *		All callers of sd_pm_entry must check the return status
9872  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9873  *		of DDI_FAILURE indicates the device failed to power up.
9874  *		In this case un_pm_count has been adjusted so the result
9875  *		on exit is still powered down, ie. count is less than 0.
9876  *		Calling sd_pm_exit with this count value hits an ASSERT.
9877  *
9878  * Return Code: DDI_SUCCESS or DDI_FAILURE
9879  *
9880  *     Context: Kernel thread context.
9881  */
9882 
9883 static int
9884 sd_pm_entry(struct sd_lun *un)
9885 {
9886 	int return_status = DDI_SUCCESS;
9887 
9888 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9889 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9890 
9891 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9892 
9893 	if (un->un_f_pm_is_enabled == FALSE) {
9894 		SD_TRACE(SD_LOG_IO_PM, un,
9895 		    "sd_pm_entry: exiting, PM not enabled\n");
9896 		return (return_status);
9897 	}
9898 
9899 	/*
9900 	 * Just increment a counter if PM is enabled. On the transition from
9901 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9902 	 * the count with each IO and mark the device as idle when the count
9903 	 * hits 0.
9904 	 *
9905 	 * If the count is less than 0 the device is powered down. If a powered
9906 	 * down device is successfully powered up then the count must be
9907 	 * incremented to reflect the power up. Note that it'll get incremented
9908 	 * a second time to become busy.
9909 	 *
9910 	 * Because the following has the potential to change the device state
9911 	 * and must release the un_pm_mutex to do so, only one thread can be
9912 	 * allowed through at a time.
9913 	 */
9914 
9915 	mutex_enter(&un->un_pm_mutex);
9916 	while (un->un_pm_busy == TRUE) {
9917 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9918 	}
9919 	un->un_pm_busy = TRUE;
9920 
9921 	if (un->un_pm_count < 1) {
9922 
9923 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9924 
9925 		/*
9926 		 * Indicate we are now busy so the framework won't attempt to
9927 		 * power down the device. This call will only fail if either
9928 		 * we passed a bad component number or the device has no
9929 		 * components. Neither of these should ever happen.
9930 		 */
9931 		mutex_exit(&un->un_pm_mutex);
9932 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9933 		ASSERT(return_status == DDI_SUCCESS);
9934 
9935 		mutex_enter(&un->un_pm_mutex);
9936 
9937 		if (un->un_pm_count < 0) {
9938 			mutex_exit(&un->un_pm_mutex);
9939 
9940 			SD_TRACE(SD_LOG_IO_PM, un,
9941 			    "sd_pm_entry: power up component\n");
9942 
9943 			/*
9944 			 * pm_raise_power will cause sdpower to be called
9945 			 * which brings the device power level to the
9946 			 * desired state, ON in this case. If successful,
9947 			 * un_pm_count and un_power_level will be updated
9948 			 * appropriately.
9949 			 */
9950 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9951 			    SD_SPINDLE_ON);
9952 
9953 			mutex_enter(&un->un_pm_mutex);
9954 
9955 			if (return_status != DDI_SUCCESS) {
9956 				/*
9957 				 * Power up failed.
9958 				 * Idle the device and adjust the count
9959 				 * so the result on exit is that we're
9960 				 * still powered down, ie. count is less than 0.
9961 				 */
9962 				SD_TRACE(SD_LOG_IO_PM, un,
9963 				    "sd_pm_entry: power up failed,"
9964 				    " idle the component\n");
9965 
9966 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9967 				un->un_pm_count--;
9968 			} else {
9969 				/*
9970 				 * Device is powered up, verify the
9971 				 * count is non-negative.
9972 				 * This is debug only.
9973 				 */
9974 				ASSERT(un->un_pm_count == 0);
9975 			}
9976 		}
9977 
9978 		if (return_status == DDI_SUCCESS) {
9979 			/*
9980 			 * For performance, now that the device has been tagged
9981 			 * as busy, and it's known to be powered up, update the
9982 			 * chain types to use jump tables that do not include
9983 			 * pm. This significantly lowers the overhead and
9984 			 * therefore improves performance.
9985 			 */
9986 
9987 			mutex_exit(&un->un_pm_mutex);
9988 			mutex_enter(SD_MUTEX(un));
9989 			SD_TRACE(SD_LOG_IO_PM, un,
9990 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9991 			    un->un_uscsi_chain_type);
9992 
9993 			if (un->un_f_non_devbsize_supported) {
9994 				un->un_buf_chain_type =
9995 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9996 			} else {
9997 				un->un_buf_chain_type =
9998 				    SD_CHAIN_INFO_DISK_NO_PM;
9999 			}
10000 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
10001 
10002 			SD_TRACE(SD_LOG_IO_PM, un,
10003 			    "             changed  uscsi_chain_type to   %d\n",
10004 			    un->un_uscsi_chain_type);
10005 			mutex_exit(SD_MUTEX(un));
10006 			mutex_enter(&un->un_pm_mutex);
10007 
10008 			if (un->un_pm_idle_timeid == NULL) {
10009 				/* 300 ms. */
10010 				un->un_pm_idle_timeid =
10011 				    timeout(sd_pm_idletimeout_handler, un,
10012 				    (drv_usectohz((clock_t)300000)));
10013 				/*
10014 				 * Include an extra call to busy which keeps the
10015 				 * device busy with-respect-to the PM layer
10016 				 * until the timer fires, at which time it'll
10017 				 * get the extra idle call.
10018 				 */
10019 				(void) pm_busy_component(SD_DEVINFO(un), 0);
10020 			}
10021 		}
10022 	}
10023 	un->un_pm_busy = FALSE;
10024 	/* Next... */
10025 	cv_signal(&un->un_pm_busy_cv);
10026 
10027 	un->un_pm_count++;
10028 
10029 	SD_TRACE(SD_LOG_IO_PM, un,
10030 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
10031 
10032 	mutex_exit(&un->un_pm_mutex);
10033 
10034 	return (return_status);
10035 }
10036 
10037 
10038 /*
10039  *    Function: sd_pm_exit
10040  *
10041  * Description: Called at the completion of a command to manage busy
10042  *		status for the device. If the device becomes idle the
10043  *		PM framework is notified.
10044  *
10045  *     Context: Kernel thread context
10046  */
10047 
10048 static void
10049 sd_pm_exit(struct sd_lun *un)
10050 {
10051 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10052 	ASSERT(!mutex_owned(&un->un_pm_mutex));
10053 
10054 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
10055 
10056 	/*
10057 	 * After attach the following flag is only read, so don't
10058 	 * take the penalty of acquiring a mutex for it.
10059 	 */
10060 	if (un->un_f_pm_is_enabled == TRUE) {
10061 
10062 		mutex_enter(&un->un_pm_mutex);
10063 		un->un_pm_count--;
10064 
10065 		SD_TRACE(SD_LOG_IO_PM, un,
10066 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
10067 
10068 		ASSERT(un->un_pm_count >= 0);
10069 		if (un->un_pm_count == 0) {
10070 			mutex_exit(&un->un_pm_mutex);
10071 
10072 			SD_TRACE(SD_LOG_IO_PM, un,
10073 			    "sd_pm_exit: idle component\n");
10074 
10075 			(void) pm_idle_component(SD_DEVINFO(un), 0);
10076 
10077 		} else {
10078 			mutex_exit(&un->un_pm_mutex);
10079 		}
10080 	}
10081 
10082 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
10083 }
10084 
10085 
10086 /*
10087  *    Function: sdopen
10088  *
10089  * Description: Driver's open(9e) entry point function.
10090  *
10091  *   Arguments: dev_i   - pointer to device number
10092  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
10093  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10094  *		cred_p  - user credential pointer
10095  *
10096  * Return Code: EINVAL
10097  *		ENXIO
10098  *		EIO
10099  *		EROFS
10100  *		EBUSY
10101  *
10102  *     Context: Kernel thread context
10103  */
10104 /* ARGSUSED */
10105 static int
10106 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
10107 {
10108 	struct sd_lun	*un;
10109 	int		nodelay;
10110 	int		part;
10111 	uint64_t	partmask;
10112 	int		instance;
10113 	dev_t		dev;
10114 	int		rval = EIO;
10115 
10116 	/* Validate the open type */
10117 	if (otyp >= OTYPCNT) {
10118 		return (EINVAL);
10119 	}
10120 
10121 	dev = *dev_p;
10122 	instance = SDUNIT(dev);
10123 	mutex_enter(&sd_detach_mutex);
10124 
10125 	/*
10126 	 * Fail the open if there is no softstate for the instance, or
10127 	 * if another thread somewhere is trying to detach the instance.
10128 	 */
10129 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
10130 	    (un->un_detach_count != 0)) {
10131 		mutex_exit(&sd_detach_mutex);
10132 		/*
10133 		 * The probe cache only needs to be cleared when open (9e) fails
10134 		 * with ENXIO (4238046).
10135 		 */
10136 		/*
10137 		 * un-conditionally clearing probe cache is ok with
10138 		 * separate sd/ssd binaries
10139 		 * x86 platform can be an issue with both parallel
10140 		 * and fibre in 1 binary
10141 		 */
10142 		sd_scsi_clear_probe_cache();
10143 		return (ENXIO);
10144 	}
10145 
10146 	/*
10147 	 * The un_layer_count is to prevent another thread in specfs from
10148 	 * trying to detach the instance, which can happen when we are
10149 	 * called from a higher-layer driver instead of thru specfs.
10150 	 * This will not be needed when DDI provides a layered driver
10151 	 * interface that allows specfs to know that an instance is in
10152 	 * use by a layered driver & should not be detached.
10153 	 *
10154 	 * Note: the semantics for layered driver opens are exactly one
10155 	 * close for every open.
10156 	 */
10157 	if (otyp == OTYP_LYR) {
10158 		un->un_layer_count++;
10159 	}
10160 
10161 	/*
10162 	 * Keep a count of the current # of opens in progress. This is because
10163 	 * some layered drivers try to call us as a regular open. This can
10164 	 * cause problems that we cannot prevent, however by keeping this count
10165 	 * we can at least keep our open and detach routines from racing against
10166 	 * each other under such conditions.
10167 	 */
10168 	un->un_opens_in_progress++;
10169 	mutex_exit(&sd_detach_mutex);
10170 
10171 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10172 	part	 = SDPART(dev);
10173 	partmask = 1 << part;
10174 
10175 	/*
10176 	 * We use a semaphore here in order to serialize
10177 	 * open and close requests on the device.
10178 	 */
10179 	sema_p(&un->un_semoclose);
10180 
10181 	mutex_enter(SD_MUTEX(un));
10182 
10183 	/*
10184 	 * All device accesses go thru sdstrategy() where we check
10185 	 * on suspend status but there could be a scsi_poll command,
10186 	 * which bypasses sdstrategy(), so we need to check pm
10187 	 * status.
10188 	 */
10189 
10190 	if (!nodelay) {
10191 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10192 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10193 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10194 		}
10195 
10196 		mutex_exit(SD_MUTEX(un));
10197 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10198 			rval = EIO;
10199 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10200 			    "sdopen: sd_pm_entry failed\n");
10201 			goto open_failed_with_pm;
10202 		}
10203 		mutex_enter(SD_MUTEX(un));
10204 	}
10205 
10206 	/* check for previous exclusive open */
10207 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10208 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10209 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10210 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10211 
10212 	if (un->un_exclopen & (partmask)) {
10213 		goto excl_open_fail;
10214 	}
10215 
10216 	if (flag & FEXCL) {
10217 		int i;
10218 		if (un->un_ocmap.lyropen[part]) {
10219 			goto excl_open_fail;
10220 		}
10221 		for (i = 0; i < (OTYPCNT - 1); i++) {
10222 			if (un->un_ocmap.regopen[i] & (partmask)) {
10223 				goto excl_open_fail;
10224 			}
10225 		}
10226 	}
10227 
10228 	/*
10229 	 * Check the write permission if this is a removable media device,
10230 	 * NDELAY has not been set, and writable permission is requested.
10231 	 *
10232 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10233 	 * attempt will fail with EIO as part of the I/O processing. This is a
10234 	 * more permissive implementation that allows the open to succeed and
10235 	 * WRITE attempts to fail when appropriate.
10236 	 */
10237 	if (un->un_f_chk_wp_open) {
10238 		if ((flag & FWRITE) && (!nodelay)) {
10239 			mutex_exit(SD_MUTEX(un));
10240 			/*
10241 			 * Defer the check for write permission on writable
10242 			 * DVD drive till sdstrategy and will not fail open even
10243 			 * if FWRITE is set as the device can be writable
10244 			 * depending upon the media and the media can change
10245 			 * after the call to open().
10246 			 */
10247 			if (un->un_f_dvdram_writable_device == FALSE) {
10248 				if (ISCD(un) || sr_check_wp(dev)) {
10249 				rval = EROFS;
10250 				mutex_enter(SD_MUTEX(un));
10251 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10252 				    "write to cd or write protected media\n");
10253 				goto open_fail;
10254 				}
10255 			}
10256 			mutex_enter(SD_MUTEX(un));
10257 		}
10258 	}
10259 
10260 	/*
10261 	 * If opening in NDELAY/NONBLOCK mode, just return.
10262 	 * Check if disk is ready and has a valid geometry later.
10263 	 */
10264 	if (!nodelay) {
10265 		mutex_exit(SD_MUTEX(un));
10266 		rval = sd_ready_and_valid(un);
10267 		mutex_enter(SD_MUTEX(un));
10268 		/*
10269 		 * Fail if device is not ready or if the number of disk
10270 		 * blocks is zero or negative for non CD devices.
10271 		 */
10272 		if ((rval != SD_READY_VALID) ||
10273 		    (!ISCD(un) && un->un_map[part].dkl_nblk <= 0)) {
10274 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10275 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10276 			    "device not ready or invalid disk block value\n");
10277 			goto open_fail;
10278 		}
10279 #if defined(__i386) || defined(__amd64)
10280 	} else {
10281 		uchar_t *cp;
10282 		/*
10283 		 * x86 requires special nodelay handling, so that p0 is
10284 		 * always defined and accessible.
10285 		 * Invalidate geometry only if device is not already open.
10286 		 */
10287 		cp = &un->un_ocmap.chkd[0];
10288 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10289 			if (*cp != (uchar_t)0) {
10290 			    break;
10291 			}
10292 			cp++;
10293 		}
10294 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10295 			un->un_f_geometry_is_valid = FALSE;
10296 		}
10297 
10298 #endif
10299 	}
10300 
10301 	if (otyp == OTYP_LYR) {
10302 		un->un_ocmap.lyropen[part]++;
10303 	} else {
10304 		un->un_ocmap.regopen[otyp] |= partmask;
10305 	}
10306 
10307 	/* Set up open and exclusive open flags */
10308 	if (flag & FEXCL) {
10309 		un->un_exclopen |= (partmask);
10310 	}
10311 
10312 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10313 	    "open of part %d type %d\n", part, otyp);
10314 
10315 	mutex_exit(SD_MUTEX(un));
10316 	if (!nodelay) {
10317 		sd_pm_exit(un);
10318 	}
10319 
10320 	sema_v(&un->un_semoclose);
10321 
10322 	mutex_enter(&sd_detach_mutex);
10323 	un->un_opens_in_progress--;
10324 	mutex_exit(&sd_detach_mutex);
10325 
10326 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10327 	return (DDI_SUCCESS);
10328 
10329 excl_open_fail:
10330 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10331 	rval = EBUSY;
10332 
10333 open_fail:
10334 	mutex_exit(SD_MUTEX(un));
10335 
10336 	/*
10337 	 * On a failed open we must exit the pm management.
10338 	 */
10339 	if (!nodelay) {
10340 		sd_pm_exit(un);
10341 	}
10342 open_failed_with_pm:
10343 	sema_v(&un->un_semoclose);
10344 
10345 	mutex_enter(&sd_detach_mutex);
10346 	un->un_opens_in_progress--;
10347 	if (otyp == OTYP_LYR) {
10348 		un->un_layer_count--;
10349 	}
10350 	mutex_exit(&sd_detach_mutex);
10351 
10352 	return (rval);
10353 }
10354 
10355 
10356 /*
10357  *    Function: sdclose
10358  *
10359  * Description: Driver's close(9e) entry point function.
10360  *
10361  *   Arguments: dev    - device number
10362  *		flag   - file status flag, informational only
10363  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10364  *		cred_p - user credential pointer
10365  *
10366  * Return Code: ENXIO
10367  *
10368  *     Context: Kernel thread context
10369  */
10370 /* ARGSUSED */
10371 static int
10372 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10373 {
10374 	struct sd_lun	*un;
10375 	uchar_t		*cp;
10376 	int		part;
10377 	int		nodelay;
10378 	int		rval = 0;
10379 
10380 	/* Validate the open type */
10381 	if (otyp >= OTYPCNT) {
10382 		return (ENXIO);
10383 	}
10384 
10385 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10386 		return (ENXIO);
10387 	}
10388 
10389 	part = SDPART(dev);
10390 	nodelay = flag & (FNDELAY | FNONBLOCK);
10391 
10392 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10393 	    "sdclose: close of part %d type %d\n", part, otyp);
10394 
10395 	/*
10396 	 * We use a semaphore here in order to serialize
10397 	 * open and close requests on the device.
10398 	 */
10399 	sema_p(&un->un_semoclose);
10400 
10401 	mutex_enter(SD_MUTEX(un));
10402 
10403 	/* Don't proceed if power is being changed. */
10404 	while (un->un_state == SD_STATE_PM_CHANGING) {
10405 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10406 	}
10407 
10408 	if (un->un_exclopen & (1 << part)) {
10409 		un->un_exclopen &= ~(1 << part);
10410 	}
10411 
10412 	/* Update the open partition map */
10413 	if (otyp == OTYP_LYR) {
10414 		un->un_ocmap.lyropen[part] -= 1;
10415 	} else {
10416 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10417 	}
10418 
10419 	cp = &un->un_ocmap.chkd[0];
10420 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10421 		if (*cp != NULL) {
10422 			break;
10423 		}
10424 		cp++;
10425 	}
10426 
10427 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10428 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10429 
10430 		/*
10431 		 * We avoid persistance upon the last close, and set
10432 		 * the throttle back to the maximum.
10433 		 */
10434 		un->un_throttle = un->un_saved_throttle;
10435 
10436 		if (un->un_state == SD_STATE_OFFLINE) {
10437 			if (un->un_f_is_fibre == FALSE) {
10438 				scsi_log(SD_DEVINFO(un), sd_label,
10439 					CE_WARN, "offline\n");
10440 			}
10441 			un->un_f_geometry_is_valid = FALSE;
10442 
10443 		} else {
10444 			/*
10445 			 * Flush any outstanding writes in NVRAM cache.
10446 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10447 			 * cmd, it may not work for non-Pluto devices.
10448 			 * SYNCHRONIZE CACHE is not required for removables,
10449 			 * except DVD-RAM drives.
10450 			 *
10451 			 * Also note: because SYNCHRONIZE CACHE is currently
10452 			 * the only command issued here that requires the
10453 			 * drive be powered up, only do the power up before
10454 			 * sending the Sync Cache command. If additional
10455 			 * commands are added which require a powered up
10456 			 * drive, the following sequence may have to change.
10457 			 *
10458 			 * And finally, note that parallel SCSI on SPARC
10459 			 * only issues a Sync Cache to DVD-RAM, a newly
10460 			 * supported device.
10461 			 */
10462 #if defined(__i386) || defined(__amd64)
10463 			if (un->un_f_sync_cache_supported ||
10464 			    un->un_f_dvdram_writable_device == TRUE) {
10465 #else
10466 			if (un->un_f_dvdram_writable_device == TRUE) {
10467 #endif
10468 				mutex_exit(SD_MUTEX(un));
10469 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10470 					rval =
10471 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10472 					    NULL);
10473 					/* ignore error if not supported */
10474 					if (rval == ENOTSUP) {
10475 						rval = 0;
10476 					} else if (rval != 0) {
10477 						rval = EIO;
10478 					}
10479 					sd_pm_exit(un);
10480 				} else {
10481 					rval = EIO;
10482 				}
10483 				mutex_enter(SD_MUTEX(un));
10484 			}
10485 
10486 			/*
10487 			 * For devices which supports DOOR_LOCK, send an ALLOW
10488 			 * MEDIA REMOVAL command, but don't get upset if it
10489 			 * fails. We need to raise the power of the drive before
10490 			 * we can call sd_send_scsi_DOORLOCK()
10491 			 */
10492 			if (un->un_f_doorlock_supported) {
10493 				mutex_exit(SD_MUTEX(un));
10494 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10495 					rval = sd_send_scsi_DOORLOCK(un,
10496 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10497 
10498 					sd_pm_exit(un);
10499 					if (ISCD(un) && (rval != 0) &&
10500 					    (nodelay != 0)) {
10501 						rval = ENXIO;
10502 					}
10503 				} else {
10504 					rval = EIO;
10505 				}
10506 				mutex_enter(SD_MUTEX(un));
10507 			}
10508 
10509 			/*
10510 			 * If a device has removable media, invalidate all
10511 			 * parameters related to media, such as geometry,
10512 			 * blocksize, and blockcount.
10513 			 */
10514 			if (un->un_f_has_removable_media) {
10515 				sr_ejected(un);
10516 			}
10517 
10518 			/*
10519 			 * Destroy the cache (if it exists) which was
10520 			 * allocated for the write maps since this is
10521 			 * the last close for this media.
10522 			 */
10523 			if (un->un_wm_cache) {
10524 				/*
10525 				 * Check if there are pending commands.
10526 				 * and if there are give a warning and
10527 				 * do not destroy the cache.
10528 				 */
10529 				if (un->un_ncmds_in_driver > 0) {
10530 					scsi_log(SD_DEVINFO(un),
10531 					    sd_label, CE_WARN,
10532 					    "Unable to clean up memory "
10533 					    "because of pending I/O\n");
10534 				} else {
10535 					kmem_cache_destroy(
10536 					    un->un_wm_cache);
10537 					un->un_wm_cache = NULL;
10538 				}
10539 			}
10540 		}
10541 	}
10542 
10543 	mutex_exit(SD_MUTEX(un));
10544 	sema_v(&un->un_semoclose);
10545 
10546 	if (otyp == OTYP_LYR) {
10547 		mutex_enter(&sd_detach_mutex);
10548 		/*
10549 		 * The detach routine may run when the layer count
10550 		 * drops to zero.
10551 		 */
10552 		un->un_layer_count--;
10553 		mutex_exit(&sd_detach_mutex);
10554 	}
10555 
10556 	return (rval);
10557 }
10558 
10559 
10560 /*
10561  *    Function: sd_ready_and_valid
10562  *
10563  * Description: Test if device is ready and has a valid geometry.
10564  *
10565  *   Arguments: dev - device number
10566  *		un  - driver soft state (unit) structure
10567  *
10568  * Return Code: SD_READY_VALID		ready and valid label
10569  *		SD_READY_NOT_VALID	ready, geom ops never applicable
10570  *		SD_NOT_READY_VALID	not ready, no label
10571  *
10572  *     Context: Never called at interrupt context.
10573  */
10574 
10575 static int
10576 sd_ready_and_valid(struct sd_lun *un)
10577 {
10578 	struct sd_errstats	*stp;
10579 	uint64_t		capacity;
10580 	uint_t			lbasize;
10581 	int			rval = SD_READY_VALID;
10582 	char			name_str[48];
10583 
10584 	ASSERT(un != NULL);
10585 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10586 
10587 	mutex_enter(SD_MUTEX(un));
10588 	/*
10589 	 * If a device has removable media, we must check if media is
10590 	 * ready when checking if this device is ready and valid.
10591 	 */
10592 	if (un->un_f_has_removable_media) {
10593 		mutex_exit(SD_MUTEX(un));
10594 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
10595 			rval = SD_NOT_READY_VALID;
10596 			mutex_enter(SD_MUTEX(un));
10597 			goto done;
10598 		}
10599 
10600 		mutex_enter(SD_MUTEX(un));
10601 		if ((un->un_f_geometry_is_valid == FALSE) ||
10602 		    (un->un_f_blockcount_is_valid == FALSE) ||
10603 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10604 
10605 			/* capacity has to be read every open. */
10606 			mutex_exit(SD_MUTEX(un));
10607 			if (sd_send_scsi_READ_CAPACITY(un, &capacity,
10608 			    &lbasize, SD_PATH_DIRECT) != 0) {
10609 				mutex_enter(SD_MUTEX(un));
10610 				un->un_f_geometry_is_valid = FALSE;
10611 				rval = SD_NOT_READY_VALID;
10612 				goto done;
10613 			} else {
10614 				mutex_enter(SD_MUTEX(un));
10615 				sd_update_block_info(un, lbasize, capacity);
10616 			}
10617 		}
10618 
10619 		/*
10620 		 * Check if the media in the device is writable or not.
10621 		 */
10622 		if ((un->un_f_geometry_is_valid == FALSE) && ISCD(un)) {
10623 			sd_check_for_writable_cd(un);
10624 		}
10625 
10626 	} else {
10627 		/*
10628 		 * Do a test unit ready to clear any unit attention from non-cd
10629 		 * devices.
10630 		 */
10631 		mutex_exit(SD_MUTEX(un));
10632 		(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
10633 		mutex_enter(SD_MUTEX(un));
10634 	}
10635 
10636 
10637 	/*
10638 	 * If this is a non 512 block device, allocate space for
10639 	 * the wmap cache. This is being done here since every time
10640 	 * a media is changed this routine will be called and the
10641 	 * block size is a function of media rather than device.
10642 	 */
10643 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
10644 		if (!(un->un_wm_cache)) {
10645 			(void) snprintf(name_str, sizeof (name_str),
10646 			    "%s%d_cache",
10647 			    ddi_driver_name(SD_DEVINFO(un)),
10648 			    ddi_get_instance(SD_DEVINFO(un)));
10649 			un->un_wm_cache = kmem_cache_create(
10650 			    name_str, sizeof (struct sd_w_map),
10651 			    8, sd_wm_cache_constructor,
10652 			    sd_wm_cache_destructor, NULL,
10653 			    (void *)un, NULL, 0);
10654 			if (!(un->un_wm_cache)) {
10655 					rval = ENOMEM;
10656 					goto done;
10657 			}
10658 		}
10659 	}
10660 
10661 	if (un->un_state == SD_STATE_NORMAL) {
10662 		/*
10663 		 * If the target is not yet ready here (defined by a TUR
10664 		 * failure), invalidate the geometry and print an 'offline'
10665 		 * message. This is a legacy message, as the state of the
10666 		 * target is not actually changed to SD_STATE_OFFLINE.
10667 		 *
10668 		 * If the TUR fails for EACCES (Reservation Conflict), it
10669 		 * means there actually is nothing wrong with the target that
10670 		 * would require invalidating the geometry, so continue in
10671 		 * that case as if the TUR was successful.
10672 		 */
10673 		int err;
10674 
10675 		mutex_exit(SD_MUTEX(un));
10676 		err = sd_send_scsi_TEST_UNIT_READY(un, 0);
10677 		mutex_enter(SD_MUTEX(un));
10678 
10679 		if ((err != 0) && (err != EACCES)) {
10680 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10681 			    "offline\n");
10682 			un->un_f_geometry_is_valid = FALSE;
10683 			rval = SD_NOT_READY_VALID;
10684 			goto done;
10685 		}
10686 	}
10687 
10688 	if (un->un_f_format_in_progress == FALSE) {
10689 		/*
10690 		 * Note: sd_validate_geometry may return TRUE, but that does
10691 		 * not necessarily mean un_f_geometry_is_valid == TRUE!
10692 		 */
10693 		rval = sd_validate_geometry(un, SD_PATH_DIRECT);
10694 		if (rval == ENOTSUP) {
10695 			if (un->un_f_geometry_is_valid == TRUE)
10696 				rval = 0;
10697 			else {
10698 				rval = SD_READY_NOT_VALID;
10699 				goto done;
10700 			}
10701 		}
10702 		if (rval != 0) {
10703 			/*
10704 			 * We don't check the validity of geometry for
10705 			 * CDROMs. Also we assume we have a good label
10706 			 * even if sd_validate_geometry returned ENOMEM.
10707 			 */
10708 			if (!ISCD(un) && rval != ENOMEM) {
10709 				rval = SD_NOT_READY_VALID;
10710 				goto done;
10711 			}
10712 		}
10713 	}
10714 
10715 #ifdef DOESNTWORK /* on eliteII, see 1118607 */
10716 	/*
10717 	 * check to see if this disk is write protected, if it is and we have
10718 	 * not set read-only, then fail
10719 	 */
10720 	if ((flag & FWRITE) && (sr_check_wp(dev))) {
10721 		New_state(un, SD_STATE_CLOSED);
10722 		goto done;
10723 	}
10724 #endif
10725 
10726 	/*
10727 	 * If this device supports DOOR_LOCK command, try and send
10728 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10729 	 * if it fails. For a CD, however, it is an error
10730 	 */
10731 	if (un->un_f_doorlock_supported) {
10732 		mutex_exit(SD_MUTEX(un));
10733 		if ((sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
10734 		    SD_PATH_DIRECT) != 0) && ISCD(un)) {
10735 			rval = SD_NOT_READY_VALID;
10736 			mutex_enter(SD_MUTEX(un));
10737 			goto done;
10738 		}
10739 		mutex_enter(SD_MUTEX(un));
10740 	}
10741 
10742 	/* The state has changed, inform the media watch routines */
10743 	un->un_mediastate = DKIO_INSERTED;
10744 	cv_broadcast(&un->un_state_cv);
10745 	rval = SD_READY_VALID;
10746 
10747 done:
10748 
10749 	/*
10750 	 * Initialize the capacity kstat value, if no media previously
10751 	 * (capacity kstat is 0) and a media has been inserted
10752 	 * (un_blockcount > 0).
10753 	 */
10754 	if (un->un_errstats != NULL) {
10755 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10756 		if ((stp->sd_capacity.value.ui64 == 0) &&
10757 		    (un->un_f_blockcount_is_valid == TRUE)) {
10758 			stp->sd_capacity.value.ui64 =
10759 			    (uint64_t)((uint64_t)un->un_blockcount *
10760 			    un->un_sys_blocksize);
10761 		}
10762 	}
10763 
10764 	mutex_exit(SD_MUTEX(un));
10765 	return (rval);
10766 }
10767 
10768 
10769 /*
10770  *    Function: sdmin
10771  *
10772  * Description: Routine to limit the size of a data transfer. Used in
10773  *		conjunction with physio(9F).
10774  *
10775  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10776  *
10777  *     Context: Kernel thread context.
10778  */
10779 
10780 static void
10781 sdmin(struct buf *bp)
10782 {
10783 	struct sd_lun	*un;
10784 	int		instance;
10785 
10786 	instance = SDUNIT(bp->b_edev);
10787 
10788 	un = ddi_get_soft_state(sd_state, instance);
10789 	ASSERT(un != NULL);
10790 
10791 	if (bp->b_bcount > un->un_max_xfer_size) {
10792 		bp->b_bcount = un->un_max_xfer_size;
10793 	}
10794 }
10795 
10796 
10797 /*
10798  *    Function: sdread
10799  *
10800  * Description: Driver's read(9e) entry point function.
10801  *
10802  *   Arguments: dev   - device number
10803  *		uio   - structure pointer describing where data is to be stored
10804  *			in user's space
10805  *		cred_p  - user credential pointer
10806  *
10807  * Return Code: ENXIO
10808  *		EIO
10809  *		EINVAL
10810  *		value returned by physio
10811  *
10812  *     Context: Kernel thread context.
10813  */
10814 /* ARGSUSED */
10815 static int
10816 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10817 {
10818 	struct sd_lun	*un = NULL;
10819 	int		secmask;
10820 	int		err;
10821 
10822 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10823 		return (ENXIO);
10824 	}
10825 
10826 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10827 
10828 	if ((un->un_f_geometry_is_valid == FALSE) && !ISCD(un)) {
10829 		mutex_enter(SD_MUTEX(un));
10830 		/*
10831 		 * Because the call to sd_ready_and_valid will issue I/O we
10832 		 * must wait here if either the device is suspended or
10833 		 * if it's power level is changing.
10834 		 */
10835 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10836 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10837 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10838 		}
10839 		un->un_ncmds_in_driver++;
10840 		mutex_exit(SD_MUTEX(un));
10841 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
10842 			mutex_enter(SD_MUTEX(un));
10843 			un->un_ncmds_in_driver--;
10844 			ASSERT(un->un_ncmds_in_driver >= 0);
10845 			mutex_exit(SD_MUTEX(un));
10846 			return (EIO);
10847 		}
10848 		mutex_enter(SD_MUTEX(un));
10849 		un->un_ncmds_in_driver--;
10850 		ASSERT(un->un_ncmds_in_driver >= 0);
10851 		mutex_exit(SD_MUTEX(un));
10852 	}
10853 
10854 	/*
10855 	 * Read requests are restricted to multiples of the system block size.
10856 	 */
10857 	secmask = un->un_sys_blocksize - 1;
10858 
10859 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10860 		SD_ERROR(SD_LOG_READ_WRITE, un,
10861 		    "sdread: file offset not modulo %d\n",
10862 		    un->un_sys_blocksize);
10863 		err = EINVAL;
10864 	} else if (uio->uio_iov->iov_len & (secmask)) {
10865 		SD_ERROR(SD_LOG_READ_WRITE, un,
10866 		    "sdread: transfer length not modulo %d\n",
10867 		    un->un_sys_blocksize);
10868 		err = EINVAL;
10869 	} else {
10870 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10871 	}
10872 	return (err);
10873 }
10874 
10875 
10876 /*
10877  *    Function: sdwrite
10878  *
10879  * Description: Driver's write(9e) entry point function.
10880  *
10881  *   Arguments: dev   - device number
10882  *		uio   - structure pointer describing where data is stored in
10883  *			user's space
10884  *		cred_p  - user credential pointer
10885  *
10886  * Return Code: ENXIO
10887  *		EIO
10888  *		EINVAL
10889  *		value returned by physio
10890  *
10891  *     Context: Kernel thread context.
10892  */
10893 /* ARGSUSED */
10894 static int
10895 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10896 {
10897 	struct sd_lun	*un = NULL;
10898 	int		secmask;
10899 	int		err;
10900 
10901 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10902 		return (ENXIO);
10903 	}
10904 
10905 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10906 
10907 	if ((un->un_f_geometry_is_valid == FALSE) && !ISCD(un)) {
10908 		mutex_enter(SD_MUTEX(un));
10909 		/*
10910 		 * Because the call to sd_ready_and_valid will issue I/O we
10911 		 * must wait here if either the device is suspended or
10912 		 * if it's power level is changing.
10913 		 */
10914 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10915 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10916 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10917 		}
10918 		un->un_ncmds_in_driver++;
10919 		mutex_exit(SD_MUTEX(un));
10920 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
10921 			mutex_enter(SD_MUTEX(un));
10922 			un->un_ncmds_in_driver--;
10923 			ASSERT(un->un_ncmds_in_driver >= 0);
10924 			mutex_exit(SD_MUTEX(un));
10925 			return (EIO);
10926 		}
10927 		mutex_enter(SD_MUTEX(un));
10928 		un->un_ncmds_in_driver--;
10929 		ASSERT(un->un_ncmds_in_driver >= 0);
10930 		mutex_exit(SD_MUTEX(un));
10931 	}
10932 
10933 	/*
10934 	 * Write requests are restricted to multiples of the system block size.
10935 	 */
10936 	secmask = un->un_sys_blocksize - 1;
10937 
10938 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10939 		SD_ERROR(SD_LOG_READ_WRITE, un,
10940 		    "sdwrite: file offset not modulo %d\n",
10941 		    un->un_sys_blocksize);
10942 		err = EINVAL;
10943 	} else if (uio->uio_iov->iov_len & (secmask)) {
10944 		SD_ERROR(SD_LOG_READ_WRITE, un,
10945 		    "sdwrite: transfer length not modulo %d\n",
10946 		    un->un_sys_blocksize);
10947 		err = EINVAL;
10948 	} else {
10949 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
10950 	}
10951 	return (err);
10952 }
10953 
10954 
10955 /*
10956  *    Function: sdaread
10957  *
10958  * Description: Driver's aread(9e) entry point function.
10959  *
10960  *   Arguments: dev   - device number
10961  *		aio   - structure pointer describing where data is to be stored
10962  *		cred_p  - user credential pointer
10963  *
10964  * Return Code: ENXIO
10965  *		EIO
10966  *		EINVAL
10967  *		value returned by aphysio
10968  *
10969  *     Context: Kernel thread context.
10970  */
10971 /* ARGSUSED */
10972 static int
10973 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10974 {
10975 	struct sd_lun	*un = NULL;
10976 	struct uio	*uio = aio->aio_uio;
10977 	int		secmask;
10978 	int		err;
10979 
10980 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10981 		return (ENXIO);
10982 	}
10983 
10984 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10985 
10986 	if ((un->un_f_geometry_is_valid == FALSE) && !ISCD(un)) {
10987 		mutex_enter(SD_MUTEX(un));
10988 		/*
10989 		 * Because the call to sd_ready_and_valid will issue I/O we
10990 		 * must wait here if either the device is suspended or
10991 		 * if it's power level is changing.
10992 		 */
10993 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10994 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10995 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10996 		}
10997 		un->un_ncmds_in_driver++;
10998 		mutex_exit(SD_MUTEX(un));
10999 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
11000 			mutex_enter(SD_MUTEX(un));
11001 			un->un_ncmds_in_driver--;
11002 			ASSERT(un->un_ncmds_in_driver >= 0);
11003 			mutex_exit(SD_MUTEX(un));
11004 			return (EIO);
11005 		}
11006 		mutex_enter(SD_MUTEX(un));
11007 		un->un_ncmds_in_driver--;
11008 		ASSERT(un->un_ncmds_in_driver >= 0);
11009 		mutex_exit(SD_MUTEX(un));
11010 	}
11011 
11012 	/*
11013 	 * Read requests are restricted to multiples of the system block size.
11014 	 */
11015 	secmask = un->un_sys_blocksize - 1;
11016 
11017 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11018 		SD_ERROR(SD_LOG_READ_WRITE, un,
11019 		    "sdaread: file offset not modulo %d\n",
11020 		    un->un_sys_blocksize);
11021 		err = EINVAL;
11022 	} else if (uio->uio_iov->iov_len & (secmask)) {
11023 		SD_ERROR(SD_LOG_READ_WRITE, un,
11024 		    "sdaread: transfer length not modulo %d\n",
11025 		    un->un_sys_blocksize);
11026 		err = EINVAL;
11027 	} else {
11028 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
11029 	}
11030 	return (err);
11031 }
11032 
11033 
11034 /*
11035  *    Function: sdawrite
11036  *
11037  * Description: Driver's awrite(9e) entry point function.
11038  *
11039  *   Arguments: dev   - device number
11040  *		aio   - structure pointer describing where data is stored
11041  *		cred_p  - user credential pointer
11042  *
11043  * Return Code: ENXIO
11044  *		EIO
11045  *		EINVAL
11046  *		value returned by aphysio
11047  *
11048  *     Context: Kernel thread context.
11049  */
11050 /* ARGSUSED */
11051 static int
11052 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11053 {
11054 	struct sd_lun	*un = NULL;
11055 	struct uio	*uio = aio->aio_uio;
11056 	int		secmask;
11057 	int		err;
11058 
11059 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11060 		return (ENXIO);
11061 	}
11062 
11063 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11064 
11065 	if ((un->un_f_geometry_is_valid == FALSE) && !ISCD(un)) {
11066 		mutex_enter(SD_MUTEX(un));
11067 		/*
11068 		 * Because the call to sd_ready_and_valid will issue I/O we
11069 		 * must wait here if either the device is suspended or
11070 		 * if it's power level is changing.
11071 		 */
11072 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11073 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11074 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11075 		}
11076 		un->un_ncmds_in_driver++;
11077 		mutex_exit(SD_MUTEX(un));
11078 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
11079 			mutex_enter(SD_MUTEX(un));
11080 			un->un_ncmds_in_driver--;
11081 			ASSERT(un->un_ncmds_in_driver >= 0);
11082 			mutex_exit(SD_MUTEX(un));
11083 			return (EIO);
11084 		}
11085 		mutex_enter(SD_MUTEX(un));
11086 		un->un_ncmds_in_driver--;
11087 		ASSERT(un->un_ncmds_in_driver >= 0);
11088 		mutex_exit(SD_MUTEX(un));
11089 	}
11090 
11091 	/*
11092 	 * Write requests are restricted to multiples of the system block size.
11093 	 */
11094 	secmask = un->un_sys_blocksize - 1;
11095 
11096 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11097 		SD_ERROR(SD_LOG_READ_WRITE, un,
11098 		    "sdawrite: file offset not modulo %d\n",
11099 		    un->un_sys_blocksize);
11100 		err = EINVAL;
11101 	} else if (uio->uio_iov->iov_len & (secmask)) {
11102 		SD_ERROR(SD_LOG_READ_WRITE, un,
11103 		    "sdawrite: transfer length not modulo %d\n",
11104 		    un->un_sys_blocksize);
11105 		err = EINVAL;
11106 	} else {
11107 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11108 	}
11109 	return (err);
11110 }
11111 
11112 
11113 
11114 
11115 
11116 /*
11117  * Driver IO processing follows the following sequence:
11118  *
11119  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11120  *         |                |                     ^
11121  *         v                v                     |
11122  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11123  *         |                |                     |                   |
11124  *         v                |                     |                   |
11125  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11126  *         |                |                     ^                   ^
11127  *         v                v                     |                   |
11128  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11129  *         |                |                     |                   |
11130  *     +---+                |                     +------------+      +-------+
11131  *     |                    |                                  |              |
11132  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11133  *     |                    v                                  |              |
11134  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11135  *     |                    |                                  ^              |
11136  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11137  *     |                    v                                  |              |
11138  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11139  *     |                    |                                  ^              |
11140  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11141  *     |                    v                                  |              |
11142  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11143  *     |                    |                                  ^              |
11144  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11145  *     |                    v                                  |              |
11146  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11147  *     |                    |                                  ^              |
11148  *     |                    |                                  |              |
11149  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11150  *                          |                           ^
11151  *                          v                           |
11152  *                   sd_core_iostart()                  |
11153  *                          |                           |
11154  *                          |                           +------>(*destroypkt)()
11155  *                          +-> sd_start_cmds() <-+     |           |
11156  *                          |                     |     |           v
11157  *                          |                     |     |  scsi_destroy_pkt(9F)
11158  *                          |                     |     |
11159  *                          +->(*initpkt)()       +- sdintr()
11160  *                          |  |                        |  |
11161  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11162  *                          |  +-> scsi_setup_cdb(9F)   |
11163  *                          |                           |
11164  *                          +--> scsi_transport(9F)     |
11165  *                                     |                |
11166  *                                     +----> SCSA ---->+
11167  *
11168  *
11169  * This code is based upon the following presumtions:
11170  *
11171  *   - iostart and iodone functions operate on buf(9S) structures. These
11172  *     functions perform the necessary operations on the buf(9S) and pass
11173  *     them along to the next function in the chain by using the macros
11174  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11175  *     (for iodone side functions).
11176  *
11177  *   - The iostart side functions may sleep. The iodone side functions
11178  *     are called under interrupt context and may NOT sleep. Therefore
11179  *     iodone side functions also may not call iostart side functions.
11180  *     (NOTE: iostart side functions should NOT sleep for memory, as
11181  *     this could result in deadlock.)
11182  *
11183  *   - An iostart side function may call its corresponding iodone side
11184  *     function directly (if necessary).
11185  *
11186  *   - In the event of an error, an iostart side function can return a buf(9S)
11187  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11188  *     b_error in the usual way of course).
11189  *
11190  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11191  *     requests to the iostart side functions.  The iostart side functions in
11192  *     this case would be called under the context of a taskq thread, so it's
11193  *     OK for them to block/sleep/spin in this case.
11194  *
11195  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11196  *     pass them along to the next function in the chain.  The corresponding
11197  *     iodone side functions must coalesce the "shadow" bufs and return
11198  *     the "original" buf to the next higher layer.
11199  *
11200  *   - The b_private field of the buf(9S) struct holds a pointer to
11201  *     an sd_xbuf struct, which contains information needed to
11202  *     construct the scsi_pkt for the command.
11203  *
11204  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11205  *     layer must acquire & release the SD_MUTEX(un) as needed.
11206  */
11207 
11208 
11209 /*
11210  * Create taskq for all targets in the system. This is created at
11211  * _init(9E) and destroyed at _fini(9E).
11212  *
11213  * Note: here we set the minalloc to a reasonably high number to ensure that
11214  * we will have an adequate supply of task entries available at interrupt time.
11215  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11216  * sd_create_taskq().  Since we do not want to sleep for allocations at
11217  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11218  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11219  * requests any one instant in time.
11220  */
11221 #define	SD_TASKQ_NUMTHREADS	8
11222 #define	SD_TASKQ_MINALLOC	256
11223 #define	SD_TASKQ_MAXALLOC	256
11224 
11225 static taskq_t	*sd_tq = NULL;
11226 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11227 
11228 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11229 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11230 
11231 /*
11232  * The following task queue is being created for the write part of
11233  * read-modify-write of non-512 block size devices.
11234  * Limit the number of threads to 1 for now. This number has been choosen
11235  * considering the fact that it applies only to dvd ram drives/MO drives
11236  * currently. Performance for which is not main criteria at this stage.
11237  * Note: It needs to be explored if we can use a single taskq in future
11238  */
11239 #define	SD_WMR_TASKQ_NUMTHREADS	1
11240 static taskq_t	*sd_wmr_tq = NULL;
11241 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11242 
11243 /*
11244  *    Function: sd_taskq_create
11245  *
11246  * Description: Create taskq thread(s) and preallocate task entries
11247  *
11248  * Return Code: Returns a pointer to the allocated taskq_t.
11249  *
11250  *     Context: Can sleep. Requires blockable context.
11251  *
11252  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11253  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11254  *		- taskq_create() will block for memory, also it will panic
11255  *		  if it cannot create the requested number of threads.
11256  *		- Currently taskq_create() creates threads that cannot be
11257  *		  swapped.
11258  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11259  *		  supply of taskq entries at interrupt time (ie, so that we
11260  *		  do not have to sleep for memory)
11261  */
11262 
11263 static void
11264 sd_taskq_create(void)
11265 {
11266 	char	taskq_name[TASKQ_NAMELEN];
11267 
11268 	ASSERT(sd_tq == NULL);
11269 	ASSERT(sd_wmr_tq == NULL);
11270 
11271 	(void) snprintf(taskq_name, sizeof (taskq_name),
11272 	    "%s_drv_taskq", sd_label);
11273 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11274 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11275 	    TASKQ_PREPOPULATE));
11276 
11277 	(void) snprintf(taskq_name, sizeof (taskq_name),
11278 	    "%s_rmw_taskq", sd_label);
11279 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11280 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11281 	    TASKQ_PREPOPULATE));
11282 }
11283 
11284 
11285 /*
11286  *    Function: sd_taskq_delete
11287  *
11288  * Description: Complementary cleanup routine for sd_taskq_create().
11289  *
11290  *     Context: Kernel thread context.
11291  */
11292 
11293 static void
11294 sd_taskq_delete(void)
11295 {
11296 	ASSERT(sd_tq != NULL);
11297 	ASSERT(sd_wmr_tq != NULL);
11298 	taskq_destroy(sd_tq);
11299 	taskq_destroy(sd_wmr_tq);
11300 	sd_tq = NULL;
11301 	sd_wmr_tq = NULL;
11302 }
11303 
11304 
11305 /*
11306  *    Function: sdstrategy
11307  *
11308  * Description: Driver's strategy (9E) entry point function.
11309  *
11310  *   Arguments: bp - pointer to buf(9S)
11311  *
11312  * Return Code: Always returns zero
11313  *
11314  *     Context: Kernel thread context.
11315  */
11316 
11317 static int
11318 sdstrategy(struct buf *bp)
11319 {
11320 	struct sd_lun *un;
11321 
11322 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11323 	if (un == NULL) {
11324 		bioerror(bp, EIO);
11325 		bp->b_resid = bp->b_bcount;
11326 		biodone(bp);
11327 		return (0);
11328 	}
11329 	/* As was done in the past, fail new cmds. if state is dumping. */
11330 	if (un->un_state == SD_STATE_DUMPING) {
11331 		bioerror(bp, ENXIO);
11332 		bp->b_resid = bp->b_bcount;
11333 		biodone(bp);
11334 		return (0);
11335 	}
11336 
11337 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11338 
11339 	/*
11340 	 * Commands may sneak in while we released the mutex in
11341 	 * DDI_SUSPEND, we should block new commands. However, old
11342 	 * commands that are still in the driver at this point should
11343 	 * still be allowed to drain.
11344 	 */
11345 	mutex_enter(SD_MUTEX(un));
11346 	/*
11347 	 * Must wait here if either the device is suspended or
11348 	 * if it's power level is changing.
11349 	 */
11350 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11351 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11352 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11353 	}
11354 
11355 	un->un_ncmds_in_driver++;
11356 
11357 	/*
11358 	 * atapi: Since we are running the CD for now in PIO mode we need to
11359 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11360 	 * the HBA's init_pkt routine.
11361 	 */
11362 	if (un->un_f_cfg_is_atapi == TRUE) {
11363 		mutex_exit(SD_MUTEX(un));
11364 		bp_mapin(bp);
11365 		mutex_enter(SD_MUTEX(un));
11366 	}
11367 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11368 	    un->un_ncmds_in_driver);
11369 
11370 	mutex_exit(SD_MUTEX(un));
11371 
11372 	/*
11373 	 * This will (eventually) allocate the sd_xbuf area and
11374 	 * call sd_xbuf_strategy().  We just want to return the
11375 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11376 	 * imized tail call which saves us a stack frame.
11377 	 */
11378 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11379 }
11380 
11381 
11382 /*
11383  *    Function: sd_xbuf_strategy
11384  *
11385  * Description: Function for initiating IO operations via the
11386  *		ddi_xbuf_qstrategy() mechanism.
11387  *
11388  *     Context: Kernel thread context.
11389  */
11390 
11391 static void
11392 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11393 {
11394 	struct sd_lun *un = arg;
11395 
11396 	ASSERT(bp != NULL);
11397 	ASSERT(xp != NULL);
11398 	ASSERT(un != NULL);
11399 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11400 
11401 	/*
11402 	 * Initialize the fields in the xbuf and save a pointer to the
11403 	 * xbuf in bp->b_private.
11404 	 */
11405 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11406 
11407 	/* Send the buf down the iostart chain */
11408 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11409 }
11410 
11411 
11412 /*
11413  *    Function: sd_xbuf_init
11414  *
11415  * Description: Prepare the given sd_xbuf struct for use.
11416  *
11417  *   Arguments: un - ptr to softstate
11418  *		bp - ptr to associated buf(9S)
11419  *		xp - ptr to associated sd_xbuf
11420  *		chain_type - IO chain type to use:
11421  *			SD_CHAIN_NULL
11422  *			SD_CHAIN_BUFIO
11423  *			SD_CHAIN_USCSI
11424  *			SD_CHAIN_DIRECT
11425  *			SD_CHAIN_DIRECT_PRIORITY
11426  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11427  *			initialization; may be NULL if none.
11428  *
11429  *     Context: Kernel thread context
11430  */
11431 
11432 static void
11433 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11434 	uchar_t chain_type, void *pktinfop)
11435 {
11436 	int index;
11437 
11438 	ASSERT(un != NULL);
11439 	ASSERT(bp != NULL);
11440 	ASSERT(xp != NULL);
11441 
11442 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11443 	    bp, chain_type);
11444 
11445 	xp->xb_un	= un;
11446 	xp->xb_pktp	= NULL;
11447 	xp->xb_pktinfo	= pktinfop;
11448 	xp->xb_private	= bp->b_private;
11449 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11450 
11451 	/*
11452 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11453 	 * upon the specified chain type to use.
11454 	 */
11455 	switch (chain_type) {
11456 	case SD_CHAIN_NULL:
11457 		/*
11458 		 * Fall thru to just use the values for the buf type, even
11459 		 * tho for the NULL chain these values will never be used.
11460 		 */
11461 		/* FALLTHRU */
11462 	case SD_CHAIN_BUFIO:
11463 		index = un->un_buf_chain_type;
11464 		break;
11465 	case SD_CHAIN_USCSI:
11466 		index = un->un_uscsi_chain_type;
11467 		break;
11468 	case SD_CHAIN_DIRECT:
11469 		index = un->un_direct_chain_type;
11470 		break;
11471 	case SD_CHAIN_DIRECT_PRIORITY:
11472 		index = un->un_priority_chain_type;
11473 		break;
11474 	default:
11475 		/* We're really broken if we ever get here... */
11476 		panic("sd_xbuf_init: illegal chain type!");
11477 		/*NOTREACHED*/
11478 	}
11479 
11480 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11481 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11482 
11483 	/*
11484 	 * It might be a bit easier to simply bzero the entire xbuf above,
11485 	 * but it turns out that since we init a fair number of members anyway,
11486 	 * we save a fair number cycles by doing explicit assignment of zero.
11487 	 */
11488 	xp->xb_pkt_flags	= 0;
11489 	xp->xb_dma_resid	= 0;
11490 	xp->xb_retry_count	= 0;
11491 	xp->xb_victim_retry_count = 0;
11492 	xp->xb_ua_retry_count	= 0;
11493 	xp->xb_sense_bp		= NULL;
11494 	xp->xb_sense_status	= 0;
11495 	xp->xb_sense_state	= 0;
11496 	xp->xb_sense_resid	= 0;
11497 
11498 	bp->b_private	= xp;
11499 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11500 	bp->b_resid	= 0;
11501 	bp->av_forw	= NULL;
11502 	bp->av_back	= NULL;
11503 	bioerror(bp, 0);
11504 
11505 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11506 }
11507 
11508 
11509 /*
11510  *    Function: sd_uscsi_strategy
11511  *
11512  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11513  *
11514  *   Arguments: bp - buf struct ptr
11515  *
11516  * Return Code: Always returns 0
11517  *
11518  *     Context: Kernel thread context
11519  */
11520 
11521 static int
11522 sd_uscsi_strategy(struct buf *bp)
11523 {
11524 	struct sd_lun		*un;
11525 	struct sd_uscsi_info	*uip;
11526 	struct sd_xbuf		*xp;
11527 	uchar_t			chain_type;
11528 
11529 	ASSERT(bp != NULL);
11530 
11531 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11532 	if (un == NULL) {
11533 		bioerror(bp, EIO);
11534 		bp->b_resid = bp->b_bcount;
11535 		biodone(bp);
11536 		return (0);
11537 	}
11538 
11539 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11540 
11541 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11542 
11543 	mutex_enter(SD_MUTEX(un));
11544 	/*
11545 	 * atapi: Since we are running the CD for now in PIO mode we need to
11546 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11547 	 * the HBA's init_pkt routine.
11548 	 */
11549 	if (un->un_f_cfg_is_atapi == TRUE) {
11550 		mutex_exit(SD_MUTEX(un));
11551 		bp_mapin(bp);
11552 		mutex_enter(SD_MUTEX(un));
11553 	}
11554 	un->un_ncmds_in_driver++;
11555 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11556 	    un->un_ncmds_in_driver);
11557 	mutex_exit(SD_MUTEX(un));
11558 
11559 	/*
11560 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11561 	 */
11562 	ASSERT(bp->b_private != NULL);
11563 	uip = (struct sd_uscsi_info *)bp->b_private;
11564 
11565 	switch (uip->ui_flags) {
11566 	case SD_PATH_DIRECT:
11567 		chain_type = SD_CHAIN_DIRECT;
11568 		break;
11569 	case SD_PATH_DIRECT_PRIORITY:
11570 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11571 		break;
11572 	default:
11573 		chain_type = SD_CHAIN_USCSI;
11574 		break;
11575 	}
11576 
11577 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
11578 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11579 
11580 	/* Use the index obtained within xbuf_init */
11581 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11582 
11583 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11584 
11585 	return (0);
11586 }
11587 
11588 
11589 /*
11590  * These routines perform raw i/o operations.
11591  */
11592 /*ARGSUSED*/
11593 static void
11594 sduscsimin(struct buf *bp)
11595 {
11596 	/*
11597 	 * do not break up because the CDB count would then
11598 	 * be incorrect and data underruns would result (incomplete
11599 	 * read/writes which would be retried and then failed, see
11600 	 * sdintr().
11601 	 */
11602 }
11603 
11604 
11605 
11606 /*
11607  *    Function: sd_send_scsi_cmd
11608  *
11609  * Description: Runs a USCSI command for user (when called thru sdioctl),
11610  *		or for the driver
11611  *
11612  *   Arguments: dev - the dev_t for the device
11613  *		incmd - ptr to a valid uscsi_cmd struct
11614  *		cdbspace - UIO_USERSPACE or UIO_SYSSPACE
11615  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11616  *		rqbufspace - UIO_USERSPACE or UIO_SYSSPACE
11617  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11618  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11619  *			to use the USCSI "direct" chain and bypass the normal
11620  *			command waitq.
11621  *
11622  * Return Code: 0 -  successful completion of the given command
11623  *		EIO - scsi_reset() failed, or see biowait()/physio() codes.
11624  *		ENXIO  - soft state not found for specified dev
11625  *		EINVAL
11626  *		EFAULT - copyin/copyout error
11627  *		return code of biowait(9F) or physio(9F):
11628  *			EIO - IO error, caller may check incmd->uscsi_status
11629  *			ENXIO
11630  *			EACCES - reservation conflict
11631  *
11632  *     Context: Waits for command to complete. Can sleep.
11633  */
11634 
11635 static int
11636 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd,
11637 	enum uio_seg cdbspace, enum uio_seg dataspace, enum uio_seg rqbufspace,
11638 	int path_flag)
11639 {
11640 	struct sd_uscsi_info	*uip;
11641 	struct uscsi_cmd	*uscmd;
11642 	struct sd_lun	*un;
11643 	struct buf	*bp;
11644 	int	rval;
11645 	int	flags;
11646 
11647 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11648 	if (un == NULL) {
11649 		return (ENXIO);
11650 	}
11651 
11652 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11653 
11654 #ifdef SDDEBUG
11655 	switch (dataspace) {
11656 	case UIO_USERSPACE:
11657 		SD_TRACE(SD_LOG_IO, un,
11658 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
11659 		break;
11660 	case UIO_SYSSPACE:
11661 		SD_TRACE(SD_LOG_IO, un,
11662 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
11663 		break;
11664 	default:
11665 		SD_TRACE(SD_LOG_IO, un,
11666 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
11667 		break;
11668 	}
11669 #endif
11670 
11671 	/*
11672 	 * Perform resets directly; no need to generate a command to do it.
11673 	 */
11674 	if (incmd->uscsi_flags & (USCSI_RESET | USCSI_RESET_ALL)) {
11675 		flags = ((incmd->uscsi_flags & USCSI_RESET_ALL) != 0) ?
11676 		    RESET_ALL : RESET_TARGET;
11677 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: Issuing reset\n");
11678 		if (scsi_reset(SD_ADDRESS(un), flags) == 0) {
11679 			/* Reset attempt was unsuccessful */
11680 			SD_TRACE(SD_LOG_IO, un,
11681 			    "sd_send_scsi_cmd: reset: failure\n");
11682 			return (EIO);
11683 		}
11684 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: reset: success\n");
11685 		return (0);
11686 	}
11687 
11688 	/* Perfunctory sanity check... */
11689 	if (incmd->uscsi_cdblen <= 0) {
11690 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11691 		    "invalid uscsi_cdblen, returning EINVAL\n");
11692 		return (EINVAL);
11693 	}
11694 
11695 	/*
11696 	 * In order to not worry about where the uscsi structure came from
11697 	 * (or where the cdb it points to came from) we're going to make
11698 	 * kmem_alloc'd copies of them here. This will also allow reference
11699 	 * to the data they contain long after this process has gone to
11700 	 * sleep and its kernel stack has been unmapped, etc.
11701 	 *
11702 	 * First get some memory for the uscsi_cmd struct and copy the
11703 	 * contents of the given uscsi_cmd struct into it.
11704 	 */
11705 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11706 	bcopy(incmd, uscmd, sizeof (struct uscsi_cmd));
11707 
11708 	SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_cmd: uscsi_cmd",
11709 	    (uchar_t *)uscmd, sizeof (struct uscsi_cmd), SD_LOG_HEX);
11710 
11711 	/*
11712 	 * Now get some space for the CDB, and copy the given CDB into
11713 	 * it. Use ddi_copyin() in case the data is in user space.
11714 	 */
11715 	uscmd->uscsi_cdb = kmem_zalloc((size_t)incmd->uscsi_cdblen, KM_SLEEP);
11716 	flags = (cdbspace == UIO_SYSSPACE) ? FKIOCTL : 0;
11717 	if (ddi_copyin(incmd->uscsi_cdb, uscmd->uscsi_cdb,
11718 	    (uint_t)incmd->uscsi_cdblen, flags) != 0) {
11719 		kmem_free(uscmd->uscsi_cdb, (size_t)incmd->uscsi_cdblen);
11720 		kmem_free(uscmd, sizeof (struct uscsi_cmd));
11721 		return (EFAULT);
11722 	}
11723 
11724 	SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_cmd: CDB",
11725 	    (uchar_t *)uscmd->uscsi_cdb, incmd->uscsi_cdblen, SD_LOG_HEX);
11726 
11727 	bp = getrbuf(KM_SLEEP);
11728 
11729 	/*
11730 	 * Allocate an sd_uscsi_info struct and fill it with the info
11731 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
11732 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
11733 	 * since we allocate the buf here in this function, we do not
11734 	 * need to preserve the prior contents of b_private.
11735 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
11736 	 */
11737 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11738 	uip->ui_flags = path_flag;
11739 	uip->ui_cmdp  = uscmd;
11740 	bp->b_private = uip;
11741 
11742 	/*
11743 	 * Initialize Request Sense buffering, if requested.
11744 	 */
11745 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
11746 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
11747 		/*
11748 		 * Here uscmd->uscsi_rqbuf currently points to the caller's
11749 		 * buffer, but we replace this with a kernel buffer that
11750 		 * we allocate to use with the sense data. The sense data
11751 		 * (if present) gets copied into this new buffer before the
11752 		 * command is completed.  Then we copy the sense data from
11753 		 * our allocated buf into the caller's buffer below. Note
11754 		 * that incmd->uscsi_rqbuf and incmd->uscsi_rqlen are used
11755 		 * below to perform the copy back to the caller's buf.
11756 		 */
11757 		uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
11758 		if (rqbufspace == UIO_USERSPACE) {
11759 			uscmd->uscsi_rqlen   = SENSE_LENGTH;
11760 			uscmd->uscsi_rqresid = SENSE_LENGTH;
11761 		} else {
11762 			uchar_t rlen = min(SENSE_LENGTH, uscmd->uscsi_rqlen);
11763 			uscmd->uscsi_rqlen   = rlen;
11764 			uscmd->uscsi_rqresid = rlen;
11765 		}
11766 	} else {
11767 		uscmd->uscsi_rqbuf = NULL;
11768 		uscmd->uscsi_rqlen   = 0;
11769 		uscmd->uscsi_rqresid = 0;
11770 	}
11771 
11772 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: rqbuf:0x%p  rqlen:%d\n",
11773 	    uscmd->uscsi_rqbuf, uscmd->uscsi_rqlen);
11774 
11775 	if (un->un_f_is_fibre == FALSE) {
11776 		/*
11777 		 * Force asynchronous mode, if necessary.  Doing this here
11778 		 * has the unfortunate effect of running other queued
11779 		 * commands async also, but since the main purpose of this
11780 		 * capability is downloading new drive firmware, we can
11781 		 * probably live with it.
11782 		 */
11783 		if ((uscmd->uscsi_flags & USCSI_ASYNC) != 0) {
11784 			if (scsi_ifgetcap(SD_ADDRESS(un), "synchronous", 1)
11785 				== 1) {
11786 				if (scsi_ifsetcap(SD_ADDRESS(un),
11787 					    "synchronous", 0, 1) == 1) {
11788 					SD_TRACE(SD_LOG_IO, un,
11789 					"sd_send_scsi_cmd: forced async ok\n");
11790 				} else {
11791 					SD_TRACE(SD_LOG_IO, un,
11792 					"sd_send_scsi_cmd:\
11793 					forced async failed\n");
11794 					rval = EINVAL;
11795 					goto done;
11796 				}
11797 			}
11798 		}
11799 
11800 		/*
11801 		 * Re-enable synchronous mode, if requested
11802 		 */
11803 		if (uscmd->uscsi_flags & USCSI_SYNC) {
11804 			if (scsi_ifgetcap(SD_ADDRESS(un), "synchronous", 1)
11805 				== 0) {
11806 				int i = scsi_ifsetcap(SD_ADDRESS(un),
11807 						"synchronous", 1, 1);
11808 				SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11809 					"re-enabled sync %s\n",
11810 					(i == 1) ? "ok" : "failed");
11811 			}
11812 		}
11813 	}
11814 
11815 	/*
11816 	 * Commands sent with priority are intended for error recovery
11817 	 * situations, and do not have retries performed.
11818 	 */
11819 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
11820 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
11821 	}
11822 
11823 	/*
11824 	 * If we're going to do actual I/O, let physio do all the right things
11825 	 */
11826 	if (uscmd->uscsi_buflen != 0) {
11827 		struct iovec	aiov;
11828 		struct uio	auio;
11829 		struct uio	*uio = &auio;
11830 
11831 		bzero(&auio, sizeof (struct uio));
11832 		bzero(&aiov, sizeof (struct iovec));
11833 		aiov.iov_base = uscmd->uscsi_bufaddr;
11834 		aiov.iov_len  = uscmd->uscsi_buflen;
11835 		uio->uio_iov  = &aiov;
11836 
11837 		uio->uio_iovcnt  = 1;
11838 		uio->uio_resid   = uscmd->uscsi_buflen;
11839 		uio->uio_segflg  = dataspace;
11840 
11841 		/*
11842 		 * physio() will block here until the command completes....
11843 		 */
11844 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: calling physio.\n");
11845 
11846 		rval = physio(sd_uscsi_strategy, bp, dev,
11847 		    ((uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE),
11848 		    sduscsimin, uio);
11849 
11850 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11851 		    "returned from physio with 0x%x\n", rval);
11852 
11853 	} else {
11854 		/*
11855 		 * We have to mimic what physio would do here! Argh!
11856 		 */
11857 		bp->b_flags  = B_BUSY |
11858 		    ((uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE);
11859 		bp->b_edev   = dev;
11860 		bp->b_dev    = cmpdev(dev);	/* maybe unnecessary? */
11861 		bp->b_bcount = 0;
11862 		bp->b_blkno  = 0;
11863 
11864 		SD_TRACE(SD_LOG_IO, un,
11865 		    "sd_send_scsi_cmd: calling sd_uscsi_strategy...\n");
11866 
11867 		(void) sd_uscsi_strategy(bp);
11868 
11869 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: calling biowait\n");
11870 
11871 		rval = biowait(bp);
11872 
11873 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11874 		    "returned from  biowait with 0x%x\n", rval);
11875 	}
11876 
11877 done:
11878 
11879 #ifdef SDDEBUG
11880 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11881 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
11882 	    uscmd->uscsi_status, uscmd->uscsi_resid);
11883 	if (uscmd->uscsi_bufaddr != NULL) {
11884 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11885 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
11886 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
11887 		if (dataspace == UIO_SYSSPACE) {
11888 			SD_DUMP_MEMORY(un, SD_LOG_IO,
11889 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
11890 			    uscmd->uscsi_buflen, SD_LOG_HEX);
11891 		}
11892 	}
11893 #endif
11894 
11895 	/*
11896 	 * Get the status and residual to return to the caller.
11897 	 */
11898 	incmd->uscsi_status = uscmd->uscsi_status;
11899 	incmd->uscsi_resid  = uscmd->uscsi_resid;
11900 
11901 	/*
11902 	 * If the caller wants sense data, copy back whatever sense data
11903 	 * we may have gotten, and update the relevant rqsense info.
11904 	 */
11905 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
11906 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
11907 
11908 		int rqlen = uscmd->uscsi_rqlen - uscmd->uscsi_rqresid;
11909 		rqlen = min(((int)incmd->uscsi_rqlen), rqlen);
11910 
11911 		/* Update the Request Sense status and resid */
11912 		incmd->uscsi_rqresid  = incmd->uscsi_rqlen - rqlen;
11913 		incmd->uscsi_rqstatus = uscmd->uscsi_rqstatus;
11914 
11915 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11916 		    "uscsi_rqstatus: 0x%02x  uscsi_rqresid:0x%x\n",
11917 		    incmd->uscsi_rqstatus, incmd->uscsi_rqresid);
11918 
11919 		/* Copy out the sense data for user processes */
11920 		if ((incmd->uscsi_rqbuf != NULL) && (rqlen != 0)) {
11921 			int flags =
11922 			    (rqbufspace == UIO_USERSPACE) ? 0 : FKIOCTL;
11923 			if (ddi_copyout(uscmd->uscsi_rqbuf, incmd->uscsi_rqbuf,
11924 			    rqlen, flags) != 0) {
11925 				rval = EFAULT;
11926 			}
11927 			/*
11928 			 * Note: Can't touch incmd->uscsi_rqbuf so use
11929 			 * uscmd->uscsi_rqbuf instead. They're the same.
11930 			 */
11931 			SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
11932 			    "incmd->uscsi_rqbuf: 0x%p  rqlen:%d\n",
11933 			    incmd->uscsi_rqbuf, rqlen);
11934 			SD_DUMP_MEMORY(un, SD_LOG_IO, "rq",
11935 			    (uchar_t *)uscmd->uscsi_rqbuf, rqlen, SD_LOG_HEX);
11936 		}
11937 	}
11938 
11939 	/*
11940 	 * Free allocated resources and return; mapout the buf in case it was
11941 	 * mapped in by a lower layer.
11942 	 */
11943 	bp_mapout(bp);
11944 	freerbuf(bp);
11945 	kmem_free(uip, sizeof (struct sd_uscsi_info));
11946 	if (uscmd->uscsi_rqbuf != NULL) {
11947 		kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
11948 	}
11949 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
11950 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
11951 
11952 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_cmd: exit\n");
11953 
11954 	return (rval);
11955 }
11956 
11957 
11958 /*
11959  *    Function: sd_buf_iodone
11960  *
11961  * Description: Frees the sd_xbuf & returns the buf to its originator.
11962  *
11963  *     Context: May be called from interrupt context.
11964  */
11965 /* ARGSUSED */
11966 static void
11967 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
11968 {
11969 	struct sd_xbuf *xp;
11970 
11971 	ASSERT(un != NULL);
11972 	ASSERT(bp != NULL);
11973 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11974 
11975 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
11976 
11977 	xp = SD_GET_XBUF(bp);
11978 	ASSERT(xp != NULL);
11979 
11980 	mutex_enter(SD_MUTEX(un));
11981 
11982 	/*
11983 	 * Grab time when the cmd completed.
11984 	 * This is used for determining if the system has been
11985 	 * idle long enough to make it idle to the PM framework.
11986 	 * This is for lowering the overhead, and therefore improving
11987 	 * performance per I/O operation.
11988 	 */
11989 	un->un_pm_idle_time = ddi_get_time();
11990 
11991 	un->un_ncmds_in_driver--;
11992 	ASSERT(un->un_ncmds_in_driver >= 0);
11993 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
11994 	    un->un_ncmds_in_driver);
11995 
11996 	mutex_exit(SD_MUTEX(un));
11997 
11998 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
11999 	biodone(bp);				/* bp is gone after this */
12000 
12001 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12002 }
12003 
12004 
12005 /*
12006  *    Function: sd_uscsi_iodone
12007  *
12008  * Description: Frees the sd_xbuf & returns the buf to its originator.
12009  *
12010  *     Context: May be called from interrupt context.
12011  */
12012 /* ARGSUSED */
12013 static void
12014 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12015 {
12016 	struct sd_xbuf *xp;
12017 
12018 	ASSERT(un != NULL);
12019 	ASSERT(bp != NULL);
12020 
12021 	xp = SD_GET_XBUF(bp);
12022 	ASSERT(xp != NULL);
12023 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12024 
12025 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12026 
12027 	bp->b_private = xp->xb_private;
12028 
12029 	mutex_enter(SD_MUTEX(un));
12030 
12031 	/*
12032 	 * Grab time when the cmd completed.
12033 	 * This is used for determining if the system has been
12034 	 * idle long enough to make it idle to the PM framework.
12035 	 * This is for lowering the overhead, and therefore improving
12036 	 * performance per I/O operation.
12037 	 */
12038 	un->un_pm_idle_time = ddi_get_time();
12039 
12040 	un->un_ncmds_in_driver--;
12041 	ASSERT(un->un_ncmds_in_driver >= 0);
12042 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12043 	    un->un_ncmds_in_driver);
12044 
12045 	mutex_exit(SD_MUTEX(un));
12046 
12047 	kmem_free(xp, sizeof (struct sd_xbuf));
12048 	biodone(bp);
12049 
12050 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12051 }
12052 
12053 
12054 /*
12055  *    Function: sd_mapblockaddr_iostart
12056  *
12057  * Description: Verify request lies withing the partition limits for
12058  *		the indicated minor device.  Issue "overrun" buf if
12059  *		request would exceed partition range.  Converts
12060  *		partition-relative block address to absolute.
12061  *
12062  *     Context: Can sleep
12063  *
12064  *      Issues: This follows what the old code did, in terms of accessing
12065  *		some of the partition info in the unit struct without holding
12066  *		the mutext.  This is a general issue, if the partition info
12067  *		can be altered while IO is in progress... as soon as we send
12068  *		a buf, its partitioning can be invalid before it gets to the
12069  *		device.  Probably the right fix is to move partitioning out
12070  *		of the driver entirely.
12071  */
12072 
12073 static void
12074 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12075 {
12076 	daddr_t	nblocks;	/* #blocks in the given partition */
12077 	daddr_t	blocknum;	/* Block number specified by the buf */
12078 	size_t	requested_nblocks;
12079 	size_t	available_nblocks;
12080 	int	partition;
12081 	diskaddr_t	partition_offset;
12082 	struct sd_xbuf *xp;
12083 
12084 
12085 	ASSERT(un != NULL);
12086 	ASSERT(bp != NULL);
12087 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12088 
12089 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12090 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12091 
12092 	xp = SD_GET_XBUF(bp);
12093 	ASSERT(xp != NULL);
12094 
12095 	/*
12096 	 * If the geometry is not indicated as valid, attempt to access
12097 	 * the unit & verify the geometry/label. This can be the case for
12098 	 * removable-media devices, of if the device was opened in
12099 	 * NDELAY/NONBLOCK mode.
12100 	 */
12101 	if ((un->un_f_geometry_is_valid != TRUE) &&
12102 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
12103 		/*
12104 		 * For removable devices it is possible to start an I/O
12105 		 * without a media by opening the device in nodelay mode.
12106 		 * Also for writable CDs there can be many scenarios where
12107 		 * there is no geometry yet but volume manager is trying to
12108 		 * issue a read() just because it can see TOC on the CD. So
12109 		 * do not print a message for removables.
12110 		 */
12111 		if (!un->un_f_has_removable_media) {
12112 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12113 			    "i/o to invalid geometry\n");
12114 		}
12115 		bioerror(bp, EIO);
12116 		bp->b_resid = bp->b_bcount;
12117 		SD_BEGIN_IODONE(index, un, bp);
12118 		return;
12119 	}
12120 
12121 	partition = SDPART(bp->b_edev);
12122 
12123 	/* #blocks in partition */
12124 	nblocks = un->un_map[partition].dkl_nblk;    /* #blocks in partition */
12125 
12126 	/* Use of a local variable potentially improves performance slightly */
12127 	partition_offset = un->un_offset[partition];
12128 
12129 	/*
12130 	 * blocknum is the starting block number of the request. At this
12131 	 * point it is still relative to the start of the minor device.
12132 	 */
12133 	blocknum = xp->xb_blkno;
12134 
12135 	/*
12136 	 * Legacy: If the starting block number is one past the last block
12137 	 * in the partition, do not set B_ERROR in the buf.
12138 	 */
12139 	if (blocknum == nblocks)  {
12140 		goto error_exit;
12141 	}
12142 
12143 	/*
12144 	 * Confirm that the first block of the request lies within the
12145 	 * partition limits. Also the requested number of bytes must be
12146 	 * a multiple of the system block size.
12147 	 */
12148 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12149 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
12150 		bp->b_flags |= B_ERROR;
12151 		goto error_exit;
12152 	}
12153 
12154 	/*
12155 	 * If the requsted # blocks exceeds the available # blocks, that
12156 	 * is an overrun of the partition.
12157 	 */
12158 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
12159 	available_nblocks = (size_t)(nblocks - blocknum);
12160 	ASSERT(nblocks >= blocknum);
12161 
12162 	if (requested_nblocks > available_nblocks) {
12163 		/*
12164 		 * Allocate an "overrun" buf to allow the request to proceed
12165 		 * for the amount of space available in the partition. The
12166 		 * amount not transferred will be added into the b_resid
12167 		 * when the operation is complete. The overrun buf
12168 		 * replaces the original buf here, and the original buf
12169 		 * is saved inside the overrun buf, for later use.
12170 		 */
12171 		size_t resid = SD_SYSBLOCKS2BYTES(un,
12172 		    (offset_t)(requested_nblocks - available_nblocks));
12173 		size_t count = bp->b_bcount - resid;
12174 		/*
12175 		 * Note: count is an unsigned entity thus it'll NEVER
12176 		 * be less than 0 so ASSERT the original values are
12177 		 * correct.
12178 		 */
12179 		ASSERT(bp->b_bcount >= resid);
12180 
12181 		bp = sd_bioclone_alloc(bp, count, blocknum,
12182 			(int (*)(struct buf *)) sd_mapblockaddr_iodone);
12183 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12184 		ASSERT(xp != NULL);
12185 	}
12186 
12187 	/* At this point there should be no residual for this buf. */
12188 	ASSERT(bp->b_resid == 0);
12189 
12190 	/* Convert the block number to an absolute address. */
12191 	xp->xb_blkno += partition_offset;
12192 
12193 	SD_NEXT_IOSTART(index, un, bp);
12194 
12195 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12196 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12197 
12198 	return;
12199 
12200 error_exit:
12201 	bp->b_resid = bp->b_bcount;
12202 	SD_BEGIN_IODONE(index, un, bp);
12203 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12204 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12205 }
12206 
12207 
12208 /*
12209  *    Function: sd_mapblockaddr_iodone
12210  *
12211  * Description: Completion-side processing for partition management.
12212  *
12213  *     Context: May be called under interrupt context
12214  */
12215 
12216 static void
12217 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12218 {
12219 	/* int	partition; */	/* Not used, see below. */
12220 	ASSERT(un != NULL);
12221 	ASSERT(bp != NULL);
12222 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12223 
12224 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12225 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12226 
12227 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
12228 		/*
12229 		 * We have an "overrun" buf to deal with...
12230 		 */
12231 		struct sd_xbuf	*xp;
12232 		struct buf	*obp;	/* ptr to the original buf */
12233 
12234 		xp = SD_GET_XBUF(bp);
12235 		ASSERT(xp != NULL);
12236 
12237 		/* Retrieve the pointer to the original buf */
12238 		obp = (struct buf *)xp->xb_private;
12239 		ASSERT(obp != NULL);
12240 
12241 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12242 		bioerror(obp, bp->b_error);
12243 
12244 		sd_bioclone_free(bp);
12245 
12246 		/*
12247 		 * Get back the original buf.
12248 		 * Note that since the restoration of xb_blkno below
12249 		 * was removed, the sd_xbuf is not needed.
12250 		 */
12251 		bp = obp;
12252 		/*
12253 		 * xp = SD_GET_XBUF(bp);
12254 		 * ASSERT(xp != NULL);
12255 		 */
12256 	}
12257 
12258 	/*
12259 	 * Convert sd->xb_blkno back to a minor-device relative value.
12260 	 * Note: this has been commented out, as it is not needed in the
12261 	 * current implementation of the driver (ie, since this function
12262 	 * is at the top of the layering chains, so the info will be
12263 	 * discarded) and it is in the "hot" IO path.
12264 	 *
12265 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12266 	 * xp->xb_blkno -= un->un_offset[partition];
12267 	 */
12268 
12269 	SD_NEXT_IODONE(index, un, bp);
12270 
12271 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12272 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12273 }
12274 
12275 
12276 /*
12277  *    Function: sd_mapblocksize_iostart
12278  *
12279  * Description: Convert between system block size (un->un_sys_blocksize)
12280  *		and target block size (un->un_tgt_blocksize).
12281  *
12282  *     Context: Can sleep to allocate resources.
12283  *
12284  * Assumptions: A higher layer has already performed any partition validation,
12285  *		and converted the xp->xb_blkno to an absolute value relative
12286  *		to the start of the device.
12287  *
12288  *		It is also assumed that the higher layer has implemented
12289  *		an "overrun" mechanism for the case where the request would
12290  *		read/write beyond the end of a partition.  In this case we
12291  *		assume (and ASSERT) that bp->b_resid == 0.
12292  *
12293  *		Note: The implementation for this routine assumes the target
12294  *		block size remains constant between allocation and transport.
12295  */
12296 
12297 static void
12298 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12299 {
12300 	struct sd_mapblocksize_info	*bsp;
12301 	struct sd_xbuf			*xp;
12302 	offset_t first_byte;
12303 	daddr_t	start_block, end_block;
12304 	daddr_t	request_bytes;
12305 	ushort_t is_aligned = FALSE;
12306 
12307 	ASSERT(un != NULL);
12308 	ASSERT(bp != NULL);
12309 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12310 	ASSERT(bp->b_resid == 0);
12311 
12312 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12313 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12314 
12315 	/*
12316 	 * For a non-writable CD, a write request is an error
12317 	 */
12318 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12319 	    (un->un_f_mmc_writable_media == FALSE)) {
12320 		bioerror(bp, EIO);
12321 		bp->b_resid = bp->b_bcount;
12322 		SD_BEGIN_IODONE(index, un, bp);
12323 		return;
12324 	}
12325 
12326 	/*
12327 	 * We do not need a shadow buf if the device is using
12328 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12329 	 * In this case there is no layer-private data block allocated.
12330 	 */
12331 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
12332 	    (bp->b_bcount == 0)) {
12333 		goto done;
12334 	}
12335 
12336 #if defined(__i386) || defined(__amd64)
12337 	/* We do not support non-block-aligned transfers for ROD devices */
12338 	ASSERT(!ISROD(un));
12339 #endif
12340 
12341 	xp = SD_GET_XBUF(bp);
12342 	ASSERT(xp != NULL);
12343 
12344 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12345 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12346 	    un->un_tgt_blocksize, un->un_sys_blocksize);
12347 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12348 	    "request start block:0x%x\n", xp->xb_blkno);
12349 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12350 	    "request len:0x%x\n", bp->b_bcount);
12351 
12352 	/*
12353 	 * Allocate the layer-private data area for the mapblocksize layer.
12354 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12355 	 * struct to store the pointer to their layer-private data block, but
12356 	 * each layer also has the responsibility of restoring the prior
12357 	 * contents of xb_private before returning the buf/xbuf to the
12358 	 * higher layer that sent it.
12359 	 *
12360 	 * Here we save the prior contents of xp->xb_private into the
12361 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12362 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12363 	 * the layer-private area and returning the buf/xbuf to the layer
12364 	 * that sent it.
12365 	 *
12366 	 * Note that here we use kmem_zalloc for the allocation as there are
12367 	 * parts of the mapblocksize code that expect certain fields to be
12368 	 * zero unless explicitly set to a required value.
12369 	 */
12370 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12371 	bsp->mbs_oprivate = xp->xb_private;
12372 	xp->xb_private = bsp;
12373 
12374 	/*
12375 	 * This treats the data on the disk (target) as an array of bytes.
12376 	 * first_byte is the byte offset, from the beginning of the device,
12377 	 * to the location of the request. This is converted from a
12378 	 * un->un_sys_blocksize block address to a byte offset, and then back
12379 	 * to a block address based upon a un->un_tgt_blocksize block size.
12380 	 *
12381 	 * xp->xb_blkno should be absolute upon entry into this function,
12382 	 * but, but it is based upon partitions that use the "system"
12383 	 * block size. It must be adjusted to reflect the block size of
12384 	 * the target.
12385 	 *
12386 	 * Note that end_block is actually the block that follows the last
12387 	 * block of the request, but that's what is needed for the computation.
12388 	 */
12389 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
12390 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12391 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
12392 	    un->un_tgt_blocksize;
12393 
12394 	/* request_bytes is rounded up to a multiple of the target block size */
12395 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12396 
12397 	/*
12398 	 * See if the starting address of the request and the request
12399 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12400 	 * then we do not need to allocate a shadow buf to handle the request.
12401 	 */
12402 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
12403 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12404 		is_aligned = TRUE;
12405 	}
12406 
12407 	if ((bp->b_flags & B_READ) == 0) {
12408 		/*
12409 		 * Lock the range for a write operation. An aligned request is
12410 		 * considered a simple write; otherwise the request must be a
12411 		 * read-modify-write.
12412 		 */
12413 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12414 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12415 	}
12416 
12417 	/*
12418 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12419 	 * where the READ command is generated for a read-modify-write. (The
12420 	 * write phase is deferred until after the read completes.)
12421 	 */
12422 	if (is_aligned == FALSE) {
12423 
12424 		struct sd_mapblocksize_info	*shadow_bsp;
12425 		struct sd_xbuf	*shadow_xp;
12426 		struct buf	*shadow_bp;
12427 
12428 		/*
12429 		 * Allocate the shadow buf and it associated xbuf. Note that
12430 		 * after this call the xb_blkno value in both the original
12431 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12432 		 * same: absolute relative to the start of the device, and
12433 		 * adjusted for the target block size. The b_blkno in the
12434 		 * shadow buf will also be set to this value. We should never
12435 		 * change b_blkno in the original bp however.
12436 		 *
12437 		 * Note also that the shadow buf will always need to be a
12438 		 * READ command, regardless of whether the incoming command
12439 		 * is a READ or a WRITE.
12440 		 */
12441 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
12442 		    xp->xb_blkno,
12443 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
12444 
12445 		shadow_xp = SD_GET_XBUF(shadow_bp);
12446 
12447 		/*
12448 		 * Allocate the layer-private data for the shadow buf.
12449 		 * (No need to preserve xb_private in the shadow xbuf.)
12450 		 */
12451 		shadow_xp->xb_private = shadow_bsp =
12452 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12453 
12454 		/*
12455 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
12456 		 * to figure out where the start of the user data is (based upon
12457 		 * the system block size) in the data returned by the READ
12458 		 * command (which will be based upon the target blocksize). Note
12459 		 * that this is only really used if the request is unaligned.
12460 		 */
12461 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
12462 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
12463 		ASSERT((bsp->mbs_copy_offset >= 0) &&
12464 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
12465 
12466 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
12467 
12468 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
12469 
12470 		/* Transfer the wmap (if any) to the shadow buf */
12471 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
12472 		bsp->mbs_wmp = NULL;
12473 
12474 		/*
12475 		 * The shadow buf goes on from here in place of the
12476 		 * original buf.
12477 		 */
12478 		shadow_bsp->mbs_orig_bp = bp;
12479 		bp = shadow_bp;
12480 	}
12481 
12482 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12483 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
12484 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12485 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
12486 	    request_bytes);
12487 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12488 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
12489 
12490 done:
12491 	SD_NEXT_IOSTART(index, un, bp);
12492 
12493 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12494 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
12495 }
12496 
12497 
12498 /*
12499  *    Function: sd_mapblocksize_iodone
12500  *
12501  * Description: Completion side processing for block-size mapping.
12502  *
12503  *     Context: May be called under interrupt context
12504  */
12505 
12506 static void
12507 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
12508 {
12509 	struct sd_mapblocksize_info	*bsp;
12510 	struct sd_xbuf	*xp;
12511 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
12512 	struct buf	*orig_bp;	/* ptr to the original buf */
12513 	offset_t	shadow_end;
12514 	offset_t	request_end;
12515 	offset_t	shadow_start;
12516 	ssize_t		copy_offset;
12517 	size_t		copy_length;
12518 	size_t		shortfall;
12519 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
12520 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
12521 
12522 	ASSERT(un != NULL);
12523 	ASSERT(bp != NULL);
12524 
12525 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12526 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
12527 
12528 	/*
12529 	 * There is no shadow buf or layer-private data if the target is
12530 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
12531 	 */
12532 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
12533 	    (bp->b_bcount == 0)) {
12534 		goto exit;
12535 	}
12536 
12537 	xp = SD_GET_XBUF(bp);
12538 	ASSERT(xp != NULL);
12539 
12540 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
12541 	bsp = xp->xb_private;
12542 
12543 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
12544 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
12545 
12546 	if (is_write) {
12547 		/*
12548 		 * For a WRITE request we must free up the block range that
12549 		 * we have locked up.  This holds regardless of whether this is
12550 		 * an aligned write request or a read-modify-write request.
12551 		 */
12552 		sd_range_unlock(un, bsp->mbs_wmp);
12553 		bsp->mbs_wmp = NULL;
12554 	}
12555 
12556 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
12557 		/*
12558 		 * An aligned read or write command will have no shadow buf;
12559 		 * there is not much else to do with it.
12560 		 */
12561 		goto done;
12562 	}
12563 
12564 	orig_bp = bsp->mbs_orig_bp;
12565 	ASSERT(orig_bp != NULL);
12566 	orig_xp = SD_GET_XBUF(orig_bp);
12567 	ASSERT(orig_xp != NULL);
12568 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12569 
12570 	if (!is_write && has_wmap) {
12571 		/*
12572 		 * A READ with a wmap means this is the READ phase of a
12573 		 * read-modify-write. If an error occurred on the READ then
12574 		 * we do not proceed with the WRITE phase or copy any data.
12575 		 * Just release the write maps and return with an error.
12576 		 */
12577 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
12578 			orig_bp->b_resid = orig_bp->b_bcount;
12579 			bioerror(orig_bp, bp->b_error);
12580 			sd_range_unlock(un, bsp->mbs_wmp);
12581 			goto freebuf_done;
12582 		}
12583 	}
12584 
12585 	/*
12586 	 * Here is where we set up to copy the data from the shadow buf
12587 	 * into the space associated with the original buf.
12588 	 *
12589 	 * To deal with the conversion between block sizes, these
12590 	 * computations treat the data as an array of bytes, with the
12591 	 * first byte (byte 0) corresponding to the first byte in the
12592 	 * first block on the disk.
12593 	 */
12594 
12595 	/*
12596 	 * shadow_start and shadow_len indicate the location and size of
12597 	 * the data returned with the shadow IO request.
12598 	 */
12599 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
12600 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
12601 
12602 	/*
12603 	 * copy_offset gives the offset (in bytes) from the start of the first
12604 	 * block of the READ request to the beginning of the data.  We retrieve
12605 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
12606 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
12607 	 * data to be copied (in bytes).
12608 	 */
12609 	copy_offset  = bsp->mbs_copy_offset;
12610 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
12611 	copy_length  = orig_bp->b_bcount;
12612 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
12613 
12614 	/*
12615 	 * Set up the resid and error fields of orig_bp as appropriate.
12616 	 */
12617 	if (shadow_end >= request_end) {
12618 		/* We got all the requested data; set resid to zero */
12619 		orig_bp->b_resid = 0;
12620 	} else {
12621 		/*
12622 		 * We failed to get enough data to fully satisfy the original
12623 		 * request. Just copy back whatever data we got and set
12624 		 * up the residual and error code as required.
12625 		 *
12626 		 * 'shortfall' is the amount by which the data received with the
12627 		 * shadow buf has "fallen short" of the requested amount.
12628 		 */
12629 		shortfall = (size_t)(request_end - shadow_end);
12630 
12631 		if (shortfall > orig_bp->b_bcount) {
12632 			/*
12633 			 * We did not get enough data to even partially
12634 			 * fulfill the original request.  The residual is
12635 			 * equal to the amount requested.
12636 			 */
12637 			orig_bp->b_resid = orig_bp->b_bcount;
12638 		} else {
12639 			/*
12640 			 * We did not get all the data that we requested
12641 			 * from the device, but we will try to return what
12642 			 * portion we did get.
12643 			 */
12644 			orig_bp->b_resid = shortfall;
12645 		}
12646 		ASSERT(copy_length >= orig_bp->b_resid);
12647 		copy_length  -= orig_bp->b_resid;
12648 	}
12649 
12650 	/* Propagate the error code from the shadow buf to the original buf */
12651 	bioerror(orig_bp, bp->b_error);
12652 
12653 	if (is_write) {
12654 		goto freebuf_done;	/* No data copying for a WRITE */
12655 	}
12656 
12657 	if (has_wmap) {
12658 		/*
12659 		 * This is a READ command from the READ phase of a
12660 		 * read-modify-write request. We have to copy the data given
12661 		 * by the user OVER the data returned by the READ command,
12662 		 * then convert the command from a READ to a WRITE and send
12663 		 * it back to the target.
12664 		 */
12665 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
12666 		    copy_length);
12667 
12668 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
12669 
12670 		/*
12671 		 * Dispatch the WRITE command to the taskq thread, which
12672 		 * will in turn send the command to the target. When the
12673 		 * WRITE command completes, we (sd_mapblocksize_iodone())
12674 		 * will get called again as part of the iodone chain
12675 		 * processing for it. Note that we will still be dealing
12676 		 * with the shadow buf at that point.
12677 		 */
12678 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
12679 		    KM_NOSLEEP) != 0) {
12680 			/*
12681 			 * Dispatch was successful so we are done. Return
12682 			 * without going any higher up the iodone chain. Do
12683 			 * not free up any layer-private data until after the
12684 			 * WRITE completes.
12685 			 */
12686 			return;
12687 		}
12688 
12689 		/*
12690 		 * Dispatch of the WRITE command failed; set up the error
12691 		 * condition and send this IO back up the iodone chain.
12692 		 */
12693 		bioerror(orig_bp, EIO);
12694 		orig_bp->b_resid = orig_bp->b_bcount;
12695 
12696 	} else {
12697 		/*
12698 		 * This is a regular READ request (ie, not a RMW). Copy the
12699 		 * data from the shadow buf into the original buf. The
12700 		 * copy_offset compensates for any "misalignment" between the
12701 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
12702 		 * original buf (with its un->un_sys_blocksize blocks).
12703 		 */
12704 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
12705 		    copy_length);
12706 	}
12707 
12708 freebuf_done:
12709 
12710 	/*
12711 	 * At this point we still have both the shadow buf AND the original
12712 	 * buf to deal with, as well as the layer-private data area in each.
12713 	 * Local variables are as follows:
12714 	 *
12715 	 * bp -- points to shadow buf
12716 	 * xp -- points to xbuf of shadow buf
12717 	 * bsp -- points to layer-private data area of shadow buf
12718 	 * orig_bp -- points to original buf
12719 	 *
12720 	 * First free the shadow buf and its associated xbuf, then free the
12721 	 * layer-private data area from the shadow buf. There is no need to
12722 	 * restore xb_private in the shadow xbuf.
12723 	 */
12724 	sd_shadow_buf_free(bp);
12725 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
12726 
12727 	/*
12728 	 * Now update the local variables to point to the original buf, xbuf,
12729 	 * and layer-private area.
12730 	 */
12731 	bp = orig_bp;
12732 	xp = SD_GET_XBUF(bp);
12733 	ASSERT(xp != NULL);
12734 	ASSERT(xp == orig_xp);
12735 	bsp = xp->xb_private;
12736 	ASSERT(bsp != NULL);
12737 
12738 done:
12739 	/*
12740 	 * Restore xb_private to whatever it was set to by the next higher
12741 	 * layer in the chain, then free the layer-private data area.
12742 	 */
12743 	xp->xb_private = bsp->mbs_oprivate;
12744 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
12745 
12746 exit:
12747 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
12748 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
12749 
12750 	SD_NEXT_IODONE(index, un, bp);
12751 }
12752 
12753 
12754 /*
12755  *    Function: sd_checksum_iostart
12756  *
12757  * Description: A stub function for a layer that's currently not used.
12758  *		For now just a placeholder.
12759  *
12760  *     Context: Kernel thread context
12761  */
12762 
12763 static void
12764 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
12765 {
12766 	ASSERT(un != NULL);
12767 	ASSERT(bp != NULL);
12768 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12769 	SD_NEXT_IOSTART(index, un, bp);
12770 }
12771 
12772 
12773 /*
12774  *    Function: sd_checksum_iodone
12775  *
12776  * Description: A stub function for a layer that's currently not used.
12777  *		For now just a placeholder.
12778  *
12779  *     Context: May be called under interrupt context
12780  */
12781 
12782 static void
12783 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
12784 {
12785 	ASSERT(un != NULL);
12786 	ASSERT(bp != NULL);
12787 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12788 	SD_NEXT_IODONE(index, un, bp);
12789 }
12790 
12791 
12792 /*
12793  *    Function: sd_checksum_uscsi_iostart
12794  *
12795  * Description: A stub function for a layer that's currently not used.
12796  *		For now just a placeholder.
12797  *
12798  *     Context: Kernel thread context
12799  */
12800 
12801 static void
12802 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
12803 {
12804 	ASSERT(un != NULL);
12805 	ASSERT(bp != NULL);
12806 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12807 	SD_NEXT_IOSTART(index, un, bp);
12808 }
12809 
12810 
12811 /*
12812  *    Function: sd_checksum_uscsi_iodone
12813  *
12814  * Description: A stub function for a layer that's currently not used.
12815  *		For now just a placeholder.
12816  *
12817  *     Context: May be called under interrupt context
12818  */
12819 
12820 static void
12821 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12822 {
12823 	ASSERT(un != NULL);
12824 	ASSERT(bp != NULL);
12825 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12826 	SD_NEXT_IODONE(index, un, bp);
12827 }
12828 
12829 
12830 /*
12831  *    Function: sd_pm_iostart
12832  *
12833  * Description: iostart-side routine for Power mangement.
12834  *
12835  *     Context: Kernel thread context
12836  */
12837 
12838 static void
12839 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
12840 {
12841 	ASSERT(un != NULL);
12842 	ASSERT(bp != NULL);
12843 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12844 	ASSERT(!mutex_owned(&un->un_pm_mutex));
12845 
12846 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
12847 
12848 	if (sd_pm_entry(un) != DDI_SUCCESS) {
12849 		/*
12850 		 * Set up to return the failed buf back up the 'iodone'
12851 		 * side of the calling chain.
12852 		 */
12853 		bioerror(bp, EIO);
12854 		bp->b_resid = bp->b_bcount;
12855 
12856 		SD_BEGIN_IODONE(index, un, bp);
12857 
12858 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
12859 		return;
12860 	}
12861 
12862 	SD_NEXT_IOSTART(index, un, bp);
12863 
12864 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
12865 }
12866 
12867 
12868 /*
12869  *    Function: sd_pm_iodone
12870  *
12871  * Description: iodone-side routine for power mangement.
12872  *
12873  *     Context: may be called from interrupt context
12874  */
12875 
12876 static void
12877 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
12878 {
12879 	ASSERT(un != NULL);
12880 	ASSERT(bp != NULL);
12881 	ASSERT(!mutex_owned(&un->un_pm_mutex));
12882 
12883 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
12884 
12885 	/*
12886 	 * After attach the following flag is only read, so don't
12887 	 * take the penalty of acquiring a mutex for it.
12888 	 */
12889 	if (un->un_f_pm_is_enabled == TRUE) {
12890 		sd_pm_exit(un);
12891 	}
12892 
12893 	SD_NEXT_IODONE(index, un, bp);
12894 
12895 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
12896 }
12897 
12898 
12899 /*
12900  *    Function: sd_core_iostart
12901  *
12902  * Description: Primary driver function for enqueuing buf(9S) structs from
12903  *		the system and initiating IO to the target device
12904  *
12905  *     Context: Kernel thread context. Can sleep.
12906  *
12907  * Assumptions:  - The given xp->xb_blkno is absolute
12908  *		   (ie, relative to the start of the device).
12909  *		 - The IO is to be done using the native blocksize of
12910  *		   the device, as specified in un->un_tgt_blocksize.
12911  */
12912 /* ARGSUSED */
12913 static void
12914 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
12915 {
12916 	struct sd_xbuf *xp;
12917 
12918 	ASSERT(un != NULL);
12919 	ASSERT(bp != NULL);
12920 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12921 	ASSERT(bp->b_resid == 0);
12922 
12923 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
12924 
12925 	xp = SD_GET_XBUF(bp);
12926 	ASSERT(xp != NULL);
12927 
12928 	mutex_enter(SD_MUTEX(un));
12929 
12930 	/*
12931 	 * If we are currently in the failfast state, fail any new IO
12932 	 * that has B_FAILFAST set, then return.
12933 	 */
12934 	if ((bp->b_flags & B_FAILFAST) &&
12935 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
12936 		mutex_exit(SD_MUTEX(un));
12937 		bioerror(bp, EIO);
12938 		bp->b_resid = bp->b_bcount;
12939 		SD_BEGIN_IODONE(index, un, bp);
12940 		return;
12941 	}
12942 
12943 	if (SD_IS_DIRECT_PRIORITY(xp)) {
12944 		/*
12945 		 * Priority command -- transport it immediately.
12946 		 *
12947 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
12948 		 * because all direct priority commands should be associated
12949 		 * with error recovery actions which we don't want to retry.
12950 		 */
12951 		sd_start_cmds(un, bp);
12952 	} else {
12953 		/*
12954 		 * Normal command -- add it to the wait queue, then start
12955 		 * transporting commands from the wait queue.
12956 		 */
12957 		sd_add_buf_to_waitq(un, bp);
12958 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
12959 		sd_start_cmds(un, NULL);
12960 	}
12961 
12962 	mutex_exit(SD_MUTEX(un));
12963 
12964 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
12965 }
12966 
12967 
12968 /*
12969  *    Function: sd_init_cdb_limits
12970  *
12971  * Description: This is to handle scsi_pkt initialization differences
12972  *		between the driver platforms.
12973  *
12974  *		Legacy behaviors:
12975  *
12976  *		If the block number or the sector count exceeds the
12977  *		capabilities of a Group 0 command, shift over to a
12978  *		Group 1 command. We don't blindly use Group 1
12979  *		commands because a) some drives (CDC Wren IVs) get a
12980  *		bit confused, and b) there is probably a fair amount
12981  *		of speed difference for a target to receive and decode
12982  *		a 10 byte command instead of a 6 byte command.
12983  *
12984  *		The xfer time difference of 6 vs 10 byte CDBs is
12985  *		still significant so this code is still worthwhile.
12986  *		10 byte CDBs are very inefficient with the fas HBA driver
12987  *		and older disks. Each CDB byte took 1 usec with some
12988  *		popular disks.
12989  *
12990  *     Context: Must be called at attach time
12991  */
12992 
12993 static void
12994 sd_init_cdb_limits(struct sd_lun *un)
12995 {
12996 	/*
12997 	 * Use CDB_GROUP1 commands for most devices except for
12998 	 * parallel SCSI fixed drives in which case we get better
12999 	 * performance using CDB_GROUP0 commands (where applicable).
13000 	 */
13001 	un->un_mincdb = SD_CDB_GROUP1;
13002 #if !defined(__fibre)
13003 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13004 	    !un->un_f_has_removable_media) {
13005 		un->un_mincdb = SD_CDB_GROUP0;
13006 	}
13007 #endif
13008 
13009 	/*
13010 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13011 	 * commands for fixed disks unless we are building for a 32 bit
13012 	 * kernel.
13013 	 */
13014 #ifdef _LP64
13015 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13016 	    SD_CDB_GROUP4;
13017 #else
13018 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13019 	    SD_CDB_GROUP1;
13020 #endif
13021 
13022 	/*
13023 	 * x86 systems require the PKT_DMA_PARTIAL flag
13024 	 */
13025 #if defined(__x86)
13026 	un->un_pkt_flags = PKT_DMA_PARTIAL;
13027 #else
13028 	un->un_pkt_flags = 0;
13029 #endif
13030 
13031 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13032 	    ? sizeof (struct scsi_arq_status) : 1);
13033 	un->un_cmd_timeout = (ushort_t)sd_io_time;
13034 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13035 }
13036 
13037 
13038 /*
13039  *    Function: sd_initpkt_for_buf
13040  *
13041  * Description: Allocate and initialize for transport a scsi_pkt struct,
13042  *		based upon the info specified in the given buf struct.
13043  *
13044  *		Assumes the xb_blkno in the request is absolute (ie,
13045  *		relative to the start of the device (NOT partition!).
13046  *		Also assumes that the request is using the native block
13047  *		size of the device (as returned by the READ CAPACITY
13048  *		command).
13049  *
13050  * Return Code: SD_PKT_ALLOC_SUCCESS
13051  *		SD_PKT_ALLOC_FAILURE
13052  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13053  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13054  *
13055  *     Context: Kernel thread and may be called from software interrupt context
13056  *		as part of a sdrunout callback. This function may not block or
13057  *		call routines that block
13058  */
13059 
13060 static int
13061 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13062 {
13063 	struct sd_xbuf	*xp;
13064 	struct scsi_pkt *pktp = NULL;
13065 	struct sd_lun	*un;
13066 	size_t		blockcount;
13067 	daddr_t		startblock;
13068 	int		rval;
13069 	int		cmd_flags;
13070 
13071 	ASSERT(bp != NULL);
13072 	ASSERT(pktpp != NULL);
13073 	xp = SD_GET_XBUF(bp);
13074 	ASSERT(xp != NULL);
13075 	un = SD_GET_UN(bp);
13076 	ASSERT(un != NULL);
13077 	ASSERT(mutex_owned(SD_MUTEX(un)));
13078 	ASSERT(bp->b_resid == 0);
13079 
13080 	SD_TRACE(SD_LOG_IO_CORE, un,
13081 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13082 
13083 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13084 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13085 		/*
13086 		 * Already have a scsi_pkt -- just need DMA resources.
13087 		 * We must recompute the CDB in case the mapping returns
13088 		 * a nonzero pkt_resid.
13089 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13090 		 * that is being retried, the unmap/remap of the DMA resouces
13091 		 * will result in the entire transfer starting over again
13092 		 * from the very first block.
13093 		 */
13094 		ASSERT(xp->xb_pktp != NULL);
13095 		pktp = xp->xb_pktp;
13096 	} else {
13097 		pktp = NULL;
13098 	}
13099 #endif /* __i386 || __amd64 */
13100 
13101 	startblock = xp->xb_blkno;	/* Absolute block num. */
13102 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13103 
13104 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13105 
13106 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13107 
13108 #else
13109 
13110 	cmd_flags = un->un_pkt_flags | xp->xb_pkt_flags;
13111 
13112 #endif
13113 
13114 	/*
13115 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13116 	 * call scsi_init_pkt, and build the CDB.
13117 	 */
13118 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13119 	    cmd_flags, sdrunout, (caddr_t)un,
13120 	    startblock, blockcount);
13121 
13122 	if (rval == 0) {
13123 		/*
13124 		 * Success.
13125 		 *
13126 		 * If partial DMA is being used and required for this transfer.
13127 		 * set it up here.
13128 		 */
13129 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13130 		    (pktp->pkt_resid != 0)) {
13131 
13132 			/*
13133 			 * Save the CDB length and pkt_resid for the
13134 			 * next xfer
13135 			 */
13136 			xp->xb_dma_resid = pktp->pkt_resid;
13137 
13138 			/* rezero resid */
13139 			pktp->pkt_resid = 0;
13140 
13141 		} else {
13142 			xp->xb_dma_resid = 0;
13143 		}
13144 
13145 		pktp->pkt_flags = un->un_tagflags;
13146 		pktp->pkt_time  = un->un_cmd_timeout;
13147 		pktp->pkt_comp  = sdintr;
13148 
13149 		pktp->pkt_private = bp;
13150 		*pktpp = pktp;
13151 
13152 		SD_TRACE(SD_LOG_IO_CORE, un,
13153 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13154 
13155 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13156 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13157 #endif
13158 
13159 		return (SD_PKT_ALLOC_SUCCESS);
13160 
13161 	}
13162 
13163 	/*
13164 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13165 	 * from sd_setup_rw_pkt.
13166 	 */
13167 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13168 
13169 	if (rval == SD_PKT_ALLOC_FAILURE) {
13170 		*pktpp = NULL;
13171 		/*
13172 		 * Set the driver state to RWAIT to indicate the driver
13173 		 * is waiting on resource allocations. The driver will not
13174 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13175 		 */
13176 		New_state(un, SD_STATE_RWAIT);
13177 
13178 		SD_ERROR(SD_LOG_IO_CORE, un,
13179 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13180 
13181 		if ((bp->b_flags & B_ERROR) != 0) {
13182 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13183 		}
13184 		return (SD_PKT_ALLOC_FAILURE);
13185 	} else {
13186 		/*
13187 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13188 		 *
13189 		 * This should never happen.  Maybe someone messed with the
13190 		 * kernel's minphys?
13191 		 */
13192 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13193 		    "Request rejected: too large for CDB: "
13194 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13195 		SD_ERROR(SD_LOG_IO_CORE, un,
13196 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13197 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13198 
13199 	}
13200 }
13201 
13202 
13203 /*
13204  *    Function: sd_destroypkt_for_buf
13205  *
13206  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13207  *
13208  *     Context: Kernel thread or interrupt context
13209  */
13210 
13211 static void
13212 sd_destroypkt_for_buf(struct buf *bp)
13213 {
13214 	ASSERT(bp != NULL);
13215 	ASSERT(SD_GET_UN(bp) != NULL);
13216 
13217 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13218 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13219 
13220 	ASSERT(SD_GET_PKTP(bp) != NULL);
13221 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13222 
13223 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13224 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13225 }
13226 
13227 /*
13228  *    Function: sd_setup_rw_pkt
13229  *
13230  * Description: Determines appropriate CDB group for the requested LBA
13231  *		and transfer length, calls scsi_init_pkt, and builds
13232  *		the CDB.  Do not use for partial DMA transfers except
13233  *		for the initial transfer since the CDB size must
13234  *		remain constant.
13235  *
13236  *     Context: Kernel thread and may be called from software interrupt
13237  *		context as part of a sdrunout callback. This function may not
13238  *		block or call routines that block
13239  */
13240 
13241 
13242 int
13243 sd_setup_rw_pkt(struct sd_lun *un,
13244     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13245     int (*callback)(caddr_t), caddr_t callback_arg,
13246     diskaddr_t lba, uint32_t blockcount)
13247 {
13248 	struct scsi_pkt *return_pktp;
13249 	union scsi_cdb *cdbp;
13250 	struct sd_cdbinfo *cp = NULL;
13251 	int i;
13252 
13253 	/*
13254 	 * See which size CDB to use, based upon the request.
13255 	 */
13256 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13257 
13258 		/*
13259 		 * Check lba and block count against sd_cdbtab limits.
13260 		 * In the partial DMA case, we have to use the same size
13261 		 * CDB for all the transfers.  Check lba + blockcount
13262 		 * against the max LBA so we know that segment of the
13263 		 * transfer can use the CDB we select.
13264 		 */
13265 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13266 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13267 
13268 			/*
13269 			 * The command will fit into the CDB type
13270 			 * specified by sd_cdbtab[i].
13271 			 */
13272 			cp = sd_cdbtab + i;
13273 
13274 			/*
13275 			 * Call scsi_init_pkt so we can fill in the
13276 			 * CDB.
13277 			 */
13278 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13279 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13280 			    flags, callback, callback_arg);
13281 
13282 			if (return_pktp != NULL) {
13283 
13284 				/*
13285 				 * Return new value of pkt
13286 				 */
13287 				*pktpp = return_pktp;
13288 
13289 				/*
13290 				 * To be safe, zero the CDB insuring there is
13291 				 * no leftover data from a previous command.
13292 				 */
13293 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13294 
13295 				/*
13296 				 * Handle partial DMA mapping
13297 				 */
13298 				if (return_pktp->pkt_resid != 0) {
13299 
13300 					/*
13301 					 * Not going to xfer as many blocks as
13302 					 * originally expected
13303 					 */
13304 					blockcount -=
13305 					    SD_BYTES2TGTBLOCKS(un,
13306 						return_pktp->pkt_resid);
13307 				}
13308 
13309 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13310 
13311 				/*
13312 				 * Set command byte based on the CDB
13313 				 * type we matched.
13314 				 */
13315 				cdbp->scc_cmd = cp->sc_grpmask |
13316 				    ((bp->b_flags & B_READ) ?
13317 					SCMD_READ : SCMD_WRITE);
13318 
13319 				SD_FILL_SCSI1_LUN(un, return_pktp);
13320 
13321 				/*
13322 				 * Fill in LBA and length
13323 				 */
13324 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13325 				    (cp->sc_grpcode == CDB_GROUP4) ||
13326 				    (cp->sc_grpcode == CDB_GROUP0) ||
13327 				    (cp->sc_grpcode == CDB_GROUP5));
13328 
13329 				if (cp->sc_grpcode == CDB_GROUP1) {
13330 					FORMG1ADDR(cdbp, lba);
13331 					FORMG1COUNT(cdbp, blockcount);
13332 					return (0);
13333 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13334 					FORMG4LONGADDR(cdbp, lba);
13335 					FORMG4COUNT(cdbp, blockcount);
13336 					return (0);
13337 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13338 					FORMG0ADDR(cdbp, lba);
13339 					FORMG0COUNT(cdbp, blockcount);
13340 					return (0);
13341 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13342 					FORMG5ADDR(cdbp, lba);
13343 					FORMG5COUNT(cdbp, blockcount);
13344 					return (0);
13345 				}
13346 
13347 				/*
13348 				 * It should be impossible to not match one
13349 				 * of the CDB types above, so we should never
13350 				 * reach this point.  Set the CDB command byte
13351 				 * to test-unit-ready to avoid writing
13352 				 * to somewhere we don't intend.
13353 				 */
13354 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13355 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13356 			} else {
13357 				/*
13358 				 * Couldn't get scsi_pkt
13359 				 */
13360 				return (SD_PKT_ALLOC_FAILURE);
13361 			}
13362 		}
13363 	}
13364 
13365 	/*
13366 	 * None of the available CDB types were suitable.  This really
13367 	 * should never happen:  on a 64 bit system we support
13368 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13369 	 * and on a 32 bit system we will refuse to bind to a device
13370 	 * larger than 2TB so addresses will never be larger than 32 bits.
13371 	 */
13372 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13373 }
13374 
13375 #if defined(__i386) || defined(__amd64)
13376 /*
13377  *    Function: sd_setup_next_rw_pkt
13378  *
13379  * Description: Setup packet for partial DMA transfers, except for the
13380  * 		initial transfer.  sd_setup_rw_pkt should be used for
13381  *		the initial transfer.
13382  *
13383  *     Context: Kernel thread and may be called from interrupt context.
13384  */
13385 
13386 int
13387 sd_setup_next_rw_pkt(struct sd_lun *un,
13388     struct scsi_pkt *pktp, struct buf *bp,
13389     diskaddr_t lba, uint32_t blockcount)
13390 {
13391 	uchar_t com;
13392 	union scsi_cdb *cdbp;
13393 	uchar_t cdb_group_id;
13394 
13395 	ASSERT(pktp != NULL);
13396 	ASSERT(pktp->pkt_cdbp != NULL);
13397 
13398 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13399 	com = cdbp->scc_cmd;
13400 	cdb_group_id = CDB_GROUPID(com);
13401 
13402 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13403 	    (cdb_group_id == CDB_GROUPID_1) ||
13404 	    (cdb_group_id == CDB_GROUPID_4) ||
13405 	    (cdb_group_id == CDB_GROUPID_5));
13406 
13407 	/*
13408 	 * Move pkt to the next portion of the xfer.
13409 	 * func is NULL_FUNC so we do not have to release
13410 	 * the disk mutex here.
13411 	 */
13412 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
13413 	    NULL_FUNC, NULL) == pktp) {
13414 		/* Success.  Handle partial DMA */
13415 		if (pktp->pkt_resid != 0) {
13416 			blockcount -=
13417 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
13418 		}
13419 
13420 		cdbp->scc_cmd = com;
13421 		SD_FILL_SCSI1_LUN(un, pktp);
13422 		if (cdb_group_id == CDB_GROUPID_1) {
13423 			FORMG1ADDR(cdbp, lba);
13424 			FORMG1COUNT(cdbp, blockcount);
13425 			return (0);
13426 		} else if (cdb_group_id == CDB_GROUPID_4) {
13427 			FORMG4LONGADDR(cdbp, lba);
13428 			FORMG4COUNT(cdbp, blockcount);
13429 			return (0);
13430 		} else if (cdb_group_id == CDB_GROUPID_0) {
13431 			FORMG0ADDR(cdbp, lba);
13432 			FORMG0COUNT(cdbp, blockcount);
13433 			return (0);
13434 		} else if (cdb_group_id == CDB_GROUPID_5) {
13435 			FORMG5ADDR(cdbp, lba);
13436 			FORMG5COUNT(cdbp, blockcount);
13437 			return (0);
13438 		}
13439 
13440 		/* Unreachable */
13441 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13442 	}
13443 
13444 	/*
13445 	 * Error setting up next portion of cmd transfer.
13446 	 * Something is definitely very wrong and this
13447 	 * should not happen.
13448 	 */
13449 	return (SD_PKT_ALLOC_FAILURE);
13450 }
13451 #endif /* defined(__i386) || defined(__amd64) */
13452 
13453 /*
13454  *    Function: sd_initpkt_for_uscsi
13455  *
13456  * Description: Allocate and initialize for transport a scsi_pkt struct,
13457  *		based upon the info specified in the given uscsi_cmd struct.
13458  *
13459  * Return Code: SD_PKT_ALLOC_SUCCESS
13460  *		SD_PKT_ALLOC_FAILURE
13461  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13462  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13463  *
13464  *     Context: Kernel thread and may be called from software interrupt context
13465  *		as part of a sdrunout callback. This function may not block or
13466  *		call routines that block
13467  */
13468 
13469 static int
13470 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
13471 {
13472 	struct uscsi_cmd *uscmd;
13473 	struct sd_xbuf	*xp;
13474 	struct scsi_pkt	*pktp;
13475 	struct sd_lun	*un;
13476 	uint32_t	flags = 0;
13477 
13478 	ASSERT(bp != NULL);
13479 	ASSERT(pktpp != NULL);
13480 	xp = SD_GET_XBUF(bp);
13481 	ASSERT(xp != NULL);
13482 	un = SD_GET_UN(bp);
13483 	ASSERT(un != NULL);
13484 	ASSERT(mutex_owned(SD_MUTEX(un)));
13485 
13486 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13487 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13488 	ASSERT(uscmd != NULL);
13489 
13490 	SD_TRACE(SD_LOG_IO_CORE, un,
13491 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
13492 
13493 	/*
13494 	 * Allocate the scsi_pkt for the command.
13495 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
13496 	 *	 during scsi_init_pkt time and will continue to use the
13497 	 *	 same path as long as the same scsi_pkt is used without
13498 	 *	 intervening scsi_dma_free(). Since uscsi command does
13499 	 *	 not call scsi_dmafree() before retry failed command, it
13500 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
13501 	 *	 set such that scsi_vhci can use other available path for
13502 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
13503 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
13504 	 */
13505 	pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13506 	    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13507 	    sizeof (struct scsi_arq_status), 0,
13508 	    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
13509 	    sdrunout, (caddr_t)un);
13510 
13511 	if (pktp == NULL) {
13512 		*pktpp = NULL;
13513 		/*
13514 		 * Set the driver state to RWAIT to indicate the driver
13515 		 * is waiting on resource allocations. The driver will not
13516 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13517 		 */
13518 		New_state(un, SD_STATE_RWAIT);
13519 
13520 		SD_ERROR(SD_LOG_IO_CORE, un,
13521 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
13522 
13523 		if ((bp->b_flags & B_ERROR) != 0) {
13524 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13525 		}
13526 		return (SD_PKT_ALLOC_FAILURE);
13527 	}
13528 
13529 	/*
13530 	 * We do not do DMA breakup for USCSI commands, so return failure
13531 	 * here if all the needed DMA resources were not allocated.
13532 	 */
13533 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
13534 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
13535 		scsi_destroy_pkt(pktp);
13536 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
13537 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
13538 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
13539 	}
13540 
13541 	/* Init the cdb from the given uscsi struct */
13542 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
13543 	    uscmd->uscsi_cdb[0], 0, 0, 0);
13544 
13545 	SD_FILL_SCSI1_LUN(un, pktp);
13546 
13547 	/*
13548 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
13549 	 * for listing of the supported flags.
13550 	 */
13551 
13552 	if (uscmd->uscsi_flags & USCSI_SILENT) {
13553 		flags |= FLAG_SILENT;
13554 	}
13555 
13556 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
13557 		flags |= FLAG_DIAGNOSE;
13558 	}
13559 
13560 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
13561 		flags |= FLAG_ISOLATE;
13562 	}
13563 
13564 	if (un->un_f_is_fibre == FALSE) {
13565 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
13566 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
13567 		}
13568 	}
13569 
13570 	/*
13571 	 * Set the pkt flags here so we save time later.
13572 	 * Note: These flags are NOT in the uscsi man page!!!
13573 	 */
13574 	if (uscmd->uscsi_flags & USCSI_HEAD) {
13575 		flags |= FLAG_HEAD;
13576 	}
13577 
13578 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
13579 		flags |= FLAG_NOINTR;
13580 	}
13581 
13582 	/*
13583 	 * For tagged queueing, things get a bit complicated.
13584 	 * Check first for head of queue and last for ordered queue.
13585 	 * If neither head nor order, use the default driver tag flags.
13586 	 */
13587 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
13588 		if (uscmd->uscsi_flags & USCSI_HTAG) {
13589 			flags |= FLAG_HTAG;
13590 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
13591 			flags |= FLAG_OTAG;
13592 		} else {
13593 			flags |= un->un_tagflags & FLAG_TAGMASK;
13594 		}
13595 	}
13596 
13597 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
13598 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
13599 	}
13600 
13601 	pktp->pkt_flags = flags;
13602 
13603 	/* Copy the caller's CDB into the pkt... */
13604 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
13605 
13606 	if (uscmd->uscsi_timeout == 0) {
13607 		pktp->pkt_time = un->un_uscsi_timeout;
13608 	} else {
13609 		pktp->pkt_time = uscmd->uscsi_timeout;
13610 	}
13611 
13612 	/* need it later to identify USCSI request in sdintr */
13613 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
13614 
13615 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
13616 
13617 	pktp->pkt_private = bp;
13618 	pktp->pkt_comp = sdintr;
13619 	*pktpp = pktp;
13620 
13621 	SD_TRACE(SD_LOG_IO_CORE, un,
13622 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
13623 
13624 	return (SD_PKT_ALLOC_SUCCESS);
13625 }
13626 
13627 
13628 /*
13629  *    Function: sd_destroypkt_for_uscsi
13630  *
13631  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
13632  *		IOs.. Also saves relevant info into the associated uscsi_cmd
13633  *		struct.
13634  *
13635  *     Context: May be called under interrupt context
13636  */
13637 
13638 static void
13639 sd_destroypkt_for_uscsi(struct buf *bp)
13640 {
13641 	struct uscsi_cmd *uscmd;
13642 	struct sd_xbuf	*xp;
13643 	struct scsi_pkt	*pktp;
13644 	struct sd_lun	*un;
13645 
13646 	ASSERT(bp != NULL);
13647 	xp = SD_GET_XBUF(bp);
13648 	ASSERT(xp != NULL);
13649 	un = SD_GET_UN(bp);
13650 	ASSERT(un != NULL);
13651 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13652 	pktp = SD_GET_PKTP(bp);
13653 	ASSERT(pktp != NULL);
13654 
13655 	SD_TRACE(SD_LOG_IO_CORE, un,
13656 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
13657 
13658 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13659 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13660 	ASSERT(uscmd != NULL);
13661 
13662 	/* Save the status and the residual into the uscsi_cmd struct */
13663 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
13664 	uscmd->uscsi_resid  = bp->b_resid;
13665 
13666 	/*
13667 	 * If enabled, copy any saved sense data into the area specified
13668 	 * by the uscsi command.
13669 	 */
13670 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
13671 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
13672 		/*
13673 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
13674 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
13675 		 */
13676 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
13677 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
13678 		bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf, SENSE_LENGTH);
13679 	}
13680 
13681 	/* We are done with the scsi_pkt; free it now */
13682 	ASSERT(SD_GET_PKTP(bp) != NULL);
13683 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13684 
13685 	SD_TRACE(SD_LOG_IO_CORE, un,
13686 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
13687 }
13688 
13689 
13690 /*
13691  *    Function: sd_bioclone_alloc
13692  *
13693  * Description: Allocate a buf(9S) and init it as per the given buf
13694  *		and the various arguments.  The associated sd_xbuf
13695  *		struct is (nearly) duplicated.  The struct buf *bp
13696  *		argument is saved in new_xp->xb_private.
13697  *
13698  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
13699  *		datalen - size of data area for the shadow bp
13700  *		blkno - starting LBA
13701  *		func - function pointer for b_iodone in the shadow buf. (May
13702  *			be NULL if none.)
13703  *
13704  * Return Code: Pointer to allocates buf(9S) struct
13705  *
13706  *     Context: Can sleep.
13707  */
13708 
13709 static struct buf *
13710 sd_bioclone_alloc(struct buf *bp, size_t datalen,
13711 	daddr_t blkno, int (*func)(struct buf *))
13712 {
13713 	struct	sd_lun	*un;
13714 	struct	sd_xbuf	*xp;
13715 	struct	sd_xbuf	*new_xp;
13716 	struct	buf	*new_bp;
13717 
13718 	ASSERT(bp != NULL);
13719 	xp = SD_GET_XBUF(bp);
13720 	ASSERT(xp != NULL);
13721 	un = SD_GET_UN(bp);
13722 	ASSERT(un != NULL);
13723 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13724 
13725 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
13726 	    NULL, KM_SLEEP);
13727 
13728 	new_bp->b_lblkno	= blkno;
13729 
13730 	/*
13731 	 * Allocate an xbuf for the shadow bp and copy the contents of the
13732 	 * original xbuf into it.
13733 	 */
13734 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
13735 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
13736 
13737 	/*
13738 	 * The given bp is automatically saved in the xb_private member
13739 	 * of the new xbuf.  Callers are allowed to depend on this.
13740 	 */
13741 	new_xp->xb_private = bp;
13742 
13743 	new_bp->b_private  = new_xp;
13744 
13745 	return (new_bp);
13746 }
13747 
13748 /*
13749  *    Function: sd_shadow_buf_alloc
13750  *
13751  * Description: Allocate a buf(9S) and init it as per the given buf
13752  *		and the various arguments.  The associated sd_xbuf
13753  *		struct is (nearly) duplicated.  The struct buf *bp
13754  *		argument is saved in new_xp->xb_private.
13755  *
13756  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
13757  *		datalen - size of data area for the shadow bp
13758  *		bflags - B_READ or B_WRITE (pseudo flag)
13759  *		blkno - starting LBA
13760  *		func - function pointer for b_iodone in the shadow buf. (May
13761  *			be NULL if none.)
13762  *
13763  * Return Code: Pointer to allocates buf(9S) struct
13764  *
13765  *     Context: Can sleep.
13766  */
13767 
13768 static struct buf *
13769 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
13770 	daddr_t blkno, int (*func)(struct buf *))
13771 {
13772 	struct	sd_lun	*un;
13773 	struct	sd_xbuf	*xp;
13774 	struct	sd_xbuf	*new_xp;
13775 	struct	buf	*new_bp;
13776 
13777 	ASSERT(bp != NULL);
13778 	xp = SD_GET_XBUF(bp);
13779 	ASSERT(xp != NULL);
13780 	un = SD_GET_UN(bp);
13781 	ASSERT(un != NULL);
13782 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13783 
13784 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
13785 		bp_mapin(bp);
13786 	}
13787 
13788 	bflags &= (B_READ | B_WRITE);
13789 #if defined(__i386) || defined(__amd64)
13790 	new_bp = getrbuf(KM_SLEEP);
13791 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
13792 	new_bp->b_bcount = datalen;
13793 	new_bp->b_flags	= bp->b_flags | bflags;
13794 #else
13795 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
13796 	    datalen, bflags, SLEEP_FUNC, NULL);
13797 #endif
13798 	new_bp->av_forw	= NULL;
13799 	new_bp->av_back	= NULL;
13800 	new_bp->b_dev	= bp->b_dev;
13801 	new_bp->b_blkno	= blkno;
13802 	new_bp->b_iodone = func;
13803 	new_bp->b_edev	= bp->b_edev;
13804 	new_bp->b_resid	= 0;
13805 
13806 	/* We need to preserve the B_FAILFAST flag */
13807 	if (bp->b_flags & B_FAILFAST) {
13808 		new_bp->b_flags |= B_FAILFAST;
13809 	}
13810 
13811 	/*
13812 	 * Allocate an xbuf for the shadow bp and copy the contents of the
13813 	 * original xbuf into it.
13814 	 */
13815 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
13816 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
13817 
13818 	/* Need later to copy data between the shadow buf & original buf! */
13819 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
13820 
13821 	/*
13822 	 * The given bp is automatically saved in the xb_private member
13823 	 * of the new xbuf.  Callers are allowed to depend on this.
13824 	 */
13825 	new_xp->xb_private = bp;
13826 
13827 	new_bp->b_private  = new_xp;
13828 
13829 	return (new_bp);
13830 }
13831 
13832 /*
13833  *    Function: sd_bioclone_free
13834  *
13835  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
13836  *		in the larger than partition operation.
13837  *
13838  *     Context: May be called under interrupt context
13839  */
13840 
13841 static void
13842 sd_bioclone_free(struct buf *bp)
13843 {
13844 	struct sd_xbuf	*xp;
13845 
13846 	ASSERT(bp != NULL);
13847 	xp = SD_GET_XBUF(bp);
13848 	ASSERT(xp != NULL);
13849 
13850 	/*
13851 	 * Call bp_mapout() before freeing the buf,  in case a lower
13852 	 * layer or HBA  had done a bp_mapin().  we must do this here
13853 	 * as we are the "originator" of the shadow buf.
13854 	 */
13855 	bp_mapout(bp);
13856 
13857 	/*
13858 	 * Null out b_iodone before freeing the bp, to ensure that the driver
13859 	 * never gets confused by a stale value in this field. (Just a little
13860 	 * extra defensiveness here.)
13861 	 */
13862 	bp->b_iodone = NULL;
13863 
13864 	freerbuf(bp);
13865 
13866 	kmem_free(xp, sizeof (struct sd_xbuf));
13867 }
13868 
13869 /*
13870  *    Function: sd_shadow_buf_free
13871  *
13872  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
13873  *
13874  *     Context: May be called under interrupt context
13875  */
13876 
13877 static void
13878 sd_shadow_buf_free(struct buf *bp)
13879 {
13880 	struct sd_xbuf	*xp;
13881 
13882 	ASSERT(bp != NULL);
13883 	xp = SD_GET_XBUF(bp);
13884 	ASSERT(xp != NULL);
13885 
13886 #if defined(__sparc)
13887 	/*
13888 	 * Call bp_mapout() before freeing the buf,  in case a lower
13889 	 * layer or HBA  had done a bp_mapin().  we must do this here
13890 	 * as we are the "originator" of the shadow buf.
13891 	 */
13892 	bp_mapout(bp);
13893 #endif
13894 
13895 	/*
13896 	 * Null out b_iodone before freeing the bp, to ensure that the driver
13897 	 * never gets confused by a stale value in this field. (Just a little
13898 	 * extra defensiveness here.)
13899 	 */
13900 	bp->b_iodone = NULL;
13901 
13902 #if defined(__i386) || defined(__amd64)
13903 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
13904 	freerbuf(bp);
13905 #else
13906 	scsi_free_consistent_buf(bp);
13907 #endif
13908 
13909 	kmem_free(xp, sizeof (struct sd_xbuf));
13910 }
13911 
13912 
13913 /*
13914  *    Function: sd_print_transport_rejected_message
13915  *
13916  * Description: This implements the ludicrously complex rules for printing
13917  *		a "transport rejected" message.  This is to address the
13918  *		specific problem of having a flood of this error message
13919  *		produced when a failover occurs.
13920  *
13921  *     Context: Any.
13922  */
13923 
13924 static void
13925 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
13926 	int code)
13927 {
13928 	ASSERT(un != NULL);
13929 	ASSERT(mutex_owned(SD_MUTEX(un)));
13930 	ASSERT(xp != NULL);
13931 
13932 	/*
13933 	 * Print the "transport rejected" message under the following
13934 	 * conditions:
13935 	 *
13936 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
13937 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
13938 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
13939 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
13940 	 *   scsi_transport(9F) (which indicates that the target might have
13941 	 *   gone off-line).  This uses the un->un_tran_fatal_count
13942 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
13943 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
13944 	 *   from scsi_transport().
13945 	 *
13946 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
13947 	 * the preceeding cases in order for the message to be printed.
13948 	 */
13949 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
13950 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
13951 		    (code != TRAN_FATAL_ERROR) ||
13952 		    (un->un_tran_fatal_count == 1)) {
13953 			switch (code) {
13954 			case TRAN_BADPKT:
13955 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13956 				    "transport rejected bad packet\n");
13957 				break;
13958 			case TRAN_FATAL_ERROR:
13959 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13960 				    "transport rejected fatal error\n");
13961 				break;
13962 			default:
13963 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13964 				    "transport rejected (%d)\n", code);
13965 				break;
13966 			}
13967 		}
13968 	}
13969 }
13970 
13971 
13972 /*
13973  *    Function: sd_add_buf_to_waitq
13974  *
13975  * Description: Add the given buf(9S) struct to the wait queue for the
13976  *		instance.  If sorting is enabled, then the buf is added
13977  *		to the queue via an elevator sort algorithm (a la
13978  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
13979  *		If sorting is not enabled, then the buf is just added
13980  *		to the end of the wait queue.
13981  *
13982  * Return Code: void
13983  *
13984  *     Context: Does not sleep/block, therefore technically can be called
13985  *		from any context.  However if sorting is enabled then the
13986  *		execution time is indeterminate, and may take long if
13987  *		the wait queue grows large.
13988  */
13989 
13990 static void
13991 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
13992 {
13993 	struct buf *ap;
13994 
13995 	ASSERT(bp != NULL);
13996 	ASSERT(un != NULL);
13997 	ASSERT(mutex_owned(SD_MUTEX(un)));
13998 
13999 	/* If the queue is empty, add the buf as the only entry & return. */
14000 	if (un->un_waitq_headp == NULL) {
14001 		ASSERT(un->un_waitq_tailp == NULL);
14002 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14003 		bp->av_forw = NULL;
14004 		return;
14005 	}
14006 
14007 	ASSERT(un->un_waitq_tailp != NULL);
14008 
14009 	/*
14010 	 * If sorting is disabled, just add the buf to the tail end of
14011 	 * the wait queue and return.
14012 	 */
14013 	if (un->un_f_disksort_disabled) {
14014 		un->un_waitq_tailp->av_forw = bp;
14015 		un->un_waitq_tailp = bp;
14016 		bp->av_forw = NULL;
14017 		return;
14018 	}
14019 
14020 	/*
14021 	 * Sort thru the list of requests currently on the wait queue
14022 	 * and add the new buf request at the appropriate position.
14023 	 *
14024 	 * The un->un_waitq_headp is an activity chain pointer on which
14025 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14026 	 * first queue holds those requests which are positioned after
14027 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14028 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14029 	 * Thus we implement a one way scan, retracting after reaching
14030 	 * the end of the drive to the first request on the second
14031 	 * queue, at which time it becomes the first queue.
14032 	 * A one-way scan is natural because of the way UNIX read-ahead
14033 	 * blocks are allocated.
14034 	 *
14035 	 * If we lie after the first request, then we must locate the
14036 	 * second request list and add ourselves to it.
14037 	 */
14038 	ap = un->un_waitq_headp;
14039 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14040 		while (ap->av_forw != NULL) {
14041 			/*
14042 			 * Look for an "inversion" in the (normally
14043 			 * ascending) block numbers. This indicates
14044 			 * the start of the second request list.
14045 			 */
14046 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14047 				/*
14048 				 * Search the second request list for the
14049 				 * first request at a larger block number.
14050 				 * We go before that; however if there is
14051 				 * no such request, we go at the end.
14052 				 */
14053 				do {
14054 					if (SD_GET_BLKNO(bp) <
14055 					    SD_GET_BLKNO(ap->av_forw)) {
14056 						goto insert;
14057 					}
14058 					ap = ap->av_forw;
14059 				} while (ap->av_forw != NULL);
14060 				goto insert;		/* after last */
14061 			}
14062 			ap = ap->av_forw;
14063 		}
14064 
14065 		/*
14066 		 * No inversions... we will go after the last, and
14067 		 * be the first request in the second request list.
14068 		 */
14069 		goto insert;
14070 	}
14071 
14072 	/*
14073 	 * Request is at/after the current request...
14074 	 * sort in the first request list.
14075 	 */
14076 	while (ap->av_forw != NULL) {
14077 		/*
14078 		 * We want to go after the current request (1) if
14079 		 * there is an inversion after it (i.e. it is the end
14080 		 * of the first request list), or (2) if the next
14081 		 * request is a larger block no. than our request.
14082 		 */
14083 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14084 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14085 			goto insert;
14086 		}
14087 		ap = ap->av_forw;
14088 	}
14089 
14090 	/*
14091 	 * Neither a second list nor a larger request, therefore
14092 	 * we go at the end of the first list (which is the same
14093 	 * as the end of the whole schebang).
14094 	 */
14095 insert:
14096 	bp->av_forw = ap->av_forw;
14097 	ap->av_forw = bp;
14098 
14099 	/*
14100 	 * If we inserted onto the tail end of the waitq, make sure the
14101 	 * tail pointer is updated.
14102 	 */
14103 	if (ap == un->un_waitq_tailp) {
14104 		un->un_waitq_tailp = bp;
14105 	}
14106 }
14107 
14108 
14109 /*
14110  *    Function: sd_start_cmds
14111  *
14112  * Description: Remove and transport cmds from the driver queues.
14113  *
14114  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14115  *
14116  *		immed_bp - ptr to a buf to be transported immediately. Only
14117  *		the immed_bp is transported; bufs on the waitq are not
14118  *		processed and the un_retry_bp is not checked.  If immed_bp is
14119  *		NULL, then normal queue processing is performed.
14120  *
14121  *     Context: May be called from kernel thread context, interrupt context,
14122  *		or runout callback context. This function may not block or
14123  *		call routines that block.
14124  */
14125 
14126 static void
14127 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14128 {
14129 	struct	sd_xbuf	*xp;
14130 	struct	buf	*bp;
14131 	void	(*statp)(kstat_io_t *);
14132 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14133 	void	(*saved_statp)(kstat_io_t *);
14134 #endif
14135 	int	rval;
14136 
14137 	ASSERT(un != NULL);
14138 	ASSERT(mutex_owned(SD_MUTEX(un)));
14139 	ASSERT(un->un_ncmds_in_transport >= 0);
14140 	ASSERT(un->un_throttle >= 0);
14141 
14142 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14143 
14144 	do {
14145 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14146 		saved_statp = NULL;
14147 #endif
14148 
14149 		/*
14150 		 * If we are syncing or dumping, fail the command to
14151 		 * avoid recursively calling back into scsi_transport().
14152 		 * The dump I/O itself uses a separate code path so this
14153 		 * only prevents non-dump I/O from being sent while dumping.
14154 		 * File system sync takes place before dumping begins.
14155 		 * During panic, filesystem I/O is allowed provided
14156 		 * un_in_callback is <= 1.  This is to prevent recursion
14157 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14158 		 * sd_start_cmds and so on.  See panic.c for more information
14159 		 * about the states the system can be in during panic.
14160 		 */
14161 		if ((un->un_state == SD_STATE_DUMPING) ||
14162 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14163 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14164 			    "sd_start_cmds: panicking\n");
14165 			goto exit;
14166 		}
14167 
14168 		if ((bp = immed_bp) != NULL) {
14169 			/*
14170 			 * We have a bp that must be transported immediately.
14171 			 * It's OK to transport the immed_bp here without doing
14172 			 * the throttle limit check because the immed_bp is
14173 			 * always used in a retry/recovery case. This means
14174 			 * that we know we are not at the throttle limit by
14175 			 * virtue of the fact that to get here we must have
14176 			 * already gotten a command back via sdintr(). This also
14177 			 * relies on (1) the command on un_retry_bp preventing
14178 			 * further commands from the waitq from being issued;
14179 			 * and (2) the code in sd_retry_command checking the
14180 			 * throttle limit before issuing a delayed or immediate
14181 			 * retry. This holds even if the throttle limit is
14182 			 * currently ratcheted down from its maximum value.
14183 			 */
14184 			statp = kstat_runq_enter;
14185 			if (bp == un->un_retry_bp) {
14186 				ASSERT((un->un_retry_statp == NULL) ||
14187 				    (un->un_retry_statp == kstat_waitq_enter) ||
14188 				    (un->un_retry_statp ==
14189 				    kstat_runq_back_to_waitq));
14190 				/*
14191 				 * If the waitq kstat was incremented when
14192 				 * sd_set_retry_bp() queued this bp for a retry,
14193 				 * then we must set up statp so that the waitq
14194 				 * count will get decremented correctly below.
14195 				 * Also we must clear un->un_retry_statp to
14196 				 * ensure that we do not act on a stale value
14197 				 * in this field.
14198 				 */
14199 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14200 				    (un->un_retry_statp ==
14201 				    kstat_runq_back_to_waitq)) {
14202 					statp = kstat_waitq_to_runq;
14203 				}
14204 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14205 				saved_statp = un->un_retry_statp;
14206 #endif
14207 				un->un_retry_statp = NULL;
14208 
14209 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14210 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14211 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14212 				    un, un->un_retry_bp, un->un_throttle,
14213 				    un->un_ncmds_in_transport);
14214 			} else {
14215 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14216 				    "processing priority bp:0x%p\n", bp);
14217 			}
14218 
14219 		} else if ((bp = un->un_waitq_headp) != NULL) {
14220 			/*
14221 			 * A command on the waitq is ready to go, but do not
14222 			 * send it if:
14223 			 *
14224 			 * (1) the throttle limit has been reached, or
14225 			 * (2) a retry is pending, or
14226 			 * (3) a START_STOP_UNIT callback pending, or
14227 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14228 			 *	command is pending.
14229 			 *
14230 			 * For all of these conditions, IO processing will
14231 			 * restart after the condition is cleared.
14232 			 */
14233 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14234 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14235 				    "sd_start_cmds: exiting, "
14236 				    "throttle limit reached!\n");
14237 				goto exit;
14238 			}
14239 			if (un->un_retry_bp != NULL) {
14240 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14241 				    "sd_start_cmds: exiting, retry pending!\n");
14242 				goto exit;
14243 			}
14244 			if (un->un_startstop_timeid != NULL) {
14245 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14246 				    "sd_start_cmds: exiting, "
14247 				    "START_STOP pending!\n");
14248 				goto exit;
14249 			}
14250 			if (un->un_direct_priority_timeid != NULL) {
14251 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14252 				    "sd_start_cmds: exiting, "
14253 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14254 				goto exit;
14255 			}
14256 
14257 			/* Dequeue the command */
14258 			un->un_waitq_headp = bp->av_forw;
14259 			if (un->un_waitq_headp == NULL) {
14260 				un->un_waitq_tailp = NULL;
14261 			}
14262 			bp->av_forw = NULL;
14263 			statp = kstat_waitq_to_runq;
14264 			SD_TRACE(SD_LOG_IO_CORE, un,
14265 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14266 
14267 		} else {
14268 			/* No work to do so bail out now */
14269 			SD_TRACE(SD_LOG_IO_CORE, un,
14270 			    "sd_start_cmds: no more work, exiting!\n");
14271 			goto exit;
14272 		}
14273 
14274 		/*
14275 		 * Reset the state to normal. This is the mechanism by which
14276 		 * the state transitions from either SD_STATE_RWAIT or
14277 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14278 		 * If state is SD_STATE_PM_CHANGING then this command is
14279 		 * part of the device power control and the state must
14280 		 * not be put back to normal. Doing so would would
14281 		 * allow new commands to proceed when they shouldn't,
14282 		 * the device may be going off.
14283 		 */
14284 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14285 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14286 			New_state(un, SD_STATE_NORMAL);
14287 		    }
14288 
14289 		xp = SD_GET_XBUF(bp);
14290 		ASSERT(xp != NULL);
14291 
14292 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14293 		/*
14294 		 * Allocate the scsi_pkt if we need one, or attach DMA
14295 		 * resources if we have a scsi_pkt that needs them. The
14296 		 * latter should only occur for commands that are being
14297 		 * retried.
14298 		 */
14299 		if ((xp->xb_pktp == NULL) ||
14300 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14301 #else
14302 		if (xp->xb_pktp == NULL) {
14303 #endif
14304 			/*
14305 			 * There is no scsi_pkt allocated for this buf. Call
14306 			 * the initpkt function to allocate & init one.
14307 			 *
14308 			 * The scsi_init_pkt runout callback functionality is
14309 			 * implemented as follows:
14310 			 *
14311 			 * 1) The initpkt function always calls
14312 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14313 			 *    callback routine.
14314 			 * 2) A successful packet allocation is initialized and
14315 			 *    the I/O is transported.
14316 			 * 3) The I/O associated with an allocation resource
14317 			 *    failure is left on its queue to be retried via
14318 			 *    runout or the next I/O.
14319 			 * 4) The I/O associated with a DMA error is removed
14320 			 *    from the queue and failed with EIO. Processing of
14321 			 *    the transport queues is also halted to be
14322 			 *    restarted via runout or the next I/O.
14323 			 * 5) The I/O associated with a CDB size or packet
14324 			 *    size error is removed from the queue and failed
14325 			 *    with EIO. Processing of the transport queues is
14326 			 *    continued.
14327 			 *
14328 			 * Note: there is no interface for canceling a runout
14329 			 * callback. To prevent the driver from detaching or
14330 			 * suspending while a runout is pending the driver
14331 			 * state is set to SD_STATE_RWAIT
14332 			 *
14333 			 * Note: using the scsi_init_pkt callback facility can
14334 			 * result in an I/O request persisting at the head of
14335 			 * the list which cannot be satisfied even after
14336 			 * multiple retries. In the future the driver may
14337 			 * implement some kind of maximum runout count before
14338 			 * failing an I/O.
14339 			 *
14340 			 * Note: the use of funcp below may seem superfluous,
14341 			 * but it helps warlock figure out the correct
14342 			 * initpkt function calls (see [s]sd.wlcmd).
14343 			 */
14344 			struct scsi_pkt	*pktp;
14345 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14346 
14347 			ASSERT(bp != un->un_rqs_bp);
14348 
14349 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14350 			switch ((*funcp)(bp, &pktp)) {
14351 			case  SD_PKT_ALLOC_SUCCESS:
14352 				xp->xb_pktp = pktp;
14353 				SD_TRACE(SD_LOG_IO_CORE, un,
14354 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14355 				    pktp);
14356 				goto got_pkt;
14357 
14358 			case SD_PKT_ALLOC_FAILURE:
14359 				/*
14360 				 * Temporary (hopefully) resource depletion.
14361 				 * Since retries and RQS commands always have a
14362 				 * scsi_pkt allocated, these cases should never
14363 				 * get here. So the only cases this needs to
14364 				 * handle is a bp from the waitq (which we put
14365 				 * back onto the waitq for sdrunout), or a bp
14366 				 * sent as an immed_bp (which we just fail).
14367 				 */
14368 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14369 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14370 
14371 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14372 
14373 				if (bp == immed_bp) {
14374 					/*
14375 					 * If SD_XB_DMA_FREED is clear, then
14376 					 * this is a failure to allocate a
14377 					 * scsi_pkt, and we must fail the
14378 					 * command.
14379 					 */
14380 					if ((xp->xb_pkt_flags &
14381 					    SD_XB_DMA_FREED) == 0) {
14382 						break;
14383 					}
14384 
14385 					/*
14386 					 * If this immediate command is NOT our
14387 					 * un_retry_bp, then we must fail it.
14388 					 */
14389 					if (bp != un->un_retry_bp) {
14390 						break;
14391 					}
14392 
14393 					/*
14394 					 * We get here if this cmd is our
14395 					 * un_retry_bp that was DMAFREED, but
14396 					 * scsi_init_pkt() failed to reallocate
14397 					 * DMA resources when we attempted to
14398 					 * retry it. This can happen when an
14399 					 * mpxio failover is in progress, but
14400 					 * we don't want to just fail the
14401 					 * command in this case.
14402 					 *
14403 					 * Use timeout(9F) to restart it after
14404 					 * a 100ms delay.  We don't want to
14405 					 * let sdrunout() restart it, because
14406 					 * sdrunout() is just supposed to start
14407 					 * commands that are sitting on the
14408 					 * wait queue.  The un_retry_bp stays
14409 					 * set until the command completes, but
14410 					 * sdrunout can be called many times
14411 					 * before that happens.  Since sdrunout
14412 					 * cannot tell if the un_retry_bp is
14413 					 * already in the transport, it could
14414 					 * end up calling scsi_transport() for
14415 					 * the un_retry_bp multiple times.
14416 					 *
14417 					 * Also: don't schedule the callback
14418 					 * if some other callback is already
14419 					 * pending.
14420 					 */
14421 					if (un->un_retry_statp == NULL) {
14422 						/*
14423 						 * restore the kstat pointer to
14424 						 * keep kstat counts coherent
14425 						 * when we do retry the command.
14426 						 */
14427 						un->un_retry_statp =
14428 						    saved_statp;
14429 					}
14430 
14431 					if ((un->un_startstop_timeid == NULL) &&
14432 					    (un->un_retry_timeid == NULL) &&
14433 					    (un->un_direct_priority_timeid ==
14434 					    NULL)) {
14435 
14436 						un->un_retry_timeid =
14437 						    timeout(
14438 						    sd_start_retry_command,
14439 						    un, SD_RESTART_TIMEOUT);
14440 					}
14441 					goto exit;
14442 				}
14443 
14444 #else
14445 				if (bp == immed_bp) {
14446 					break;	/* Just fail the command */
14447 				}
14448 #endif
14449 
14450 				/* Add the buf back to the head of the waitq */
14451 				bp->av_forw = un->un_waitq_headp;
14452 				un->un_waitq_headp = bp;
14453 				if (un->un_waitq_tailp == NULL) {
14454 					un->un_waitq_tailp = bp;
14455 				}
14456 				goto exit;
14457 
14458 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
14459 				/*
14460 				 * HBA DMA resource failure. Fail the command
14461 				 * and continue processing of the queues.
14462 				 */
14463 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14464 				    "sd_start_cmds: "
14465 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
14466 				break;
14467 
14468 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
14469 				/*
14470 				 * Note:x86: Partial DMA mapping not supported
14471 				 * for USCSI commands, and all the needed DMA
14472 				 * resources were not allocated.
14473 				 */
14474 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14475 				    "sd_start_cmds: "
14476 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
14477 				break;
14478 
14479 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
14480 				/*
14481 				 * Note:x86: Request cannot fit into CDB based
14482 				 * on lba and len.
14483 				 */
14484 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14485 				    "sd_start_cmds: "
14486 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
14487 				break;
14488 
14489 			default:
14490 				/* Should NEVER get here! */
14491 				panic("scsi_initpkt error");
14492 				/*NOTREACHED*/
14493 			}
14494 
14495 			/*
14496 			 * Fatal error in allocating a scsi_pkt for this buf.
14497 			 * Update kstats & return the buf with an error code.
14498 			 * We must use sd_return_failed_command_no_restart() to
14499 			 * avoid a recursive call back into sd_start_cmds().
14500 			 * However this also means that we must keep processing
14501 			 * the waitq here in order to avoid stalling.
14502 			 */
14503 			if (statp == kstat_waitq_to_runq) {
14504 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
14505 			}
14506 			sd_return_failed_command_no_restart(un, bp, EIO);
14507 			if (bp == immed_bp) {
14508 				/* immed_bp is gone by now, so clear this */
14509 				immed_bp = NULL;
14510 			}
14511 			continue;
14512 		}
14513 got_pkt:
14514 		if (bp == immed_bp) {
14515 			/* goto the head of the class.... */
14516 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
14517 		}
14518 
14519 		un->un_ncmds_in_transport++;
14520 		SD_UPDATE_KSTATS(un, statp, bp);
14521 
14522 		/*
14523 		 * Call scsi_transport() to send the command to the target.
14524 		 * According to SCSA architecture, we must drop the mutex here
14525 		 * before calling scsi_transport() in order to avoid deadlock.
14526 		 * Note that the scsi_pkt's completion routine can be executed
14527 		 * (from interrupt context) even before the call to
14528 		 * scsi_transport() returns.
14529 		 */
14530 		SD_TRACE(SD_LOG_IO_CORE, un,
14531 		    "sd_start_cmds: calling scsi_transport()\n");
14532 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
14533 
14534 		mutex_exit(SD_MUTEX(un));
14535 		rval = scsi_transport(xp->xb_pktp);
14536 		mutex_enter(SD_MUTEX(un));
14537 
14538 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14539 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
14540 
14541 		switch (rval) {
14542 		case TRAN_ACCEPT:
14543 			/* Clear this with every pkt accepted by the HBA */
14544 			un->un_tran_fatal_count = 0;
14545 			break;	/* Success; try the next cmd (if any) */
14546 
14547 		case TRAN_BUSY:
14548 			un->un_ncmds_in_transport--;
14549 			ASSERT(un->un_ncmds_in_transport >= 0);
14550 
14551 			/*
14552 			 * Don't retry request sense, the sense data
14553 			 * is lost when another request is sent.
14554 			 * Free up the rqs buf and retry
14555 			 * the original failed cmd.  Update kstat.
14556 			 */
14557 			if (bp == un->un_rqs_bp) {
14558 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14559 				bp = sd_mark_rqs_idle(un, xp);
14560 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
14561 					NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
14562 					kstat_waitq_enter);
14563 				goto exit;
14564 			}
14565 
14566 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14567 			/*
14568 			 * Free the DMA resources for the  scsi_pkt. This will
14569 			 * allow mpxio to select another path the next time
14570 			 * we call scsi_transport() with this scsi_pkt.
14571 			 * See sdintr() for the rationalization behind this.
14572 			 */
14573 			if ((un->un_f_is_fibre == TRUE) &&
14574 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14575 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
14576 				scsi_dmafree(xp->xb_pktp);
14577 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14578 			}
14579 #endif
14580 
14581 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
14582 				/*
14583 				 * Commands that are SD_PATH_DIRECT_PRIORITY
14584 				 * are for error recovery situations. These do
14585 				 * not use the normal command waitq, so if they
14586 				 * get a TRAN_BUSY we cannot put them back onto
14587 				 * the waitq for later retry. One possible
14588 				 * problem is that there could already be some
14589 				 * other command on un_retry_bp that is waiting
14590 				 * for this one to complete, so we would be
14591 				 * deadlocked if we put this command back onto
14592 				 * the waitq for later retry (since un_retry_bp
14593 				 * must complete before the driver gets back to
14594 				 * commands on the waitq).
14595 				 *
14596 				 * To avoid deadlock we must schedule a callback
14597 				 * that will restart this command after a set
14598 				 * interval.  This should keep retrying for as
14599 				 * long as the underlying transport keeps
14600 				 * returning TRAN_BUSY (just like for other
14601 				 * commands).  Use the same timeout interval as
14602 				 * for the ordinary TRAN_BUSY retry.
14603 				 */
14604 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14605 				    "sd_start_cmds: scsi_transport() returned "
14606 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
14607 
14608 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14609 				un->un_direct_priority_timeid =
14610 				    timeout(sd_start_direct_priority_command,
14611 				    bp, SD_BSY_TIMEOUT / 500);
14612 
14613 				goto exit;
14614 			}
14615 
14616 			/*
14617 			 * For TRAN_BUSY, we want to reduce the throttle value,
14618 			 * unless we are retrying a command.
14619 			 */
14620 			if (bp != un->un_retry_bp) {
14621 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
14622 			}
14623 
14624 			/*
14625 			 * Set up the bp to be tried again 10 ms later.
14626 			 * Note:x86: Is there a timeout value in the sd_lun
14627 			 * for this condition?
14628 			 */
14629 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
14630 				kstat_runq_back_to_waitq);
14631 			goto exit;
14632 
14633 		case TRAN_FATAL_ERROR:
14634 			un->un_tran_fatal_count++;
14635 			/* FALLTHRU */
14636 
14637 		case TRAN_BADPKT:
14638 		default:
14639 			un->un_ncmds_in_transport--;
14640 			ASSERT(un->un_ncmds_in_transport >= 0);
14641 
14642 			/*
14643 			 * If this is our REQUEST SENSE command with a
14644 			 * transport error, we must get back the pointers
14645 			 * to the original buf, and mark the REQUEST
14646 			 * SENSE command as "available".
14647 			 */
14648 			if (bp == un->un_rqs_bp) {
14649 				bp = sd_mark_rqs_idle(un, xp);
14650 				xp = SD_GET_XBUF(bp);
14651 			} else {
14652 				/*
14653 				 * Legacy behavior: do not update transport
14654 				 * error count for request sense commands.
14655 				 */
14656 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
14657 			}
14658 
14659 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14660 			sd_print_transport_rejected_message(un, xp, rval);
14661 
14662 			/*
14663 			 * We must use sd_return_failed_command_no_restart() to
14664 			 * avoid a recursive call back into sd_start_cmds().
14665 			 * However this also means that we must keep processing
14666 			 * the waitq here in order to avoid stalling.
14667 			 */
14668 			sd_return_failed_command_no_restart(un, bp, EIO);
14669 
14670 			/*
14671 			 * Notify any threads waiting in sd_ddi_suspend() that
14672 			 * a command completion has occurred.
14673 			 */
14674 			if (un->un_state == SD_STATE_SUSPENDED) {
14675 				cv_broadcast(&un->un_disk_busy_cv);
14676 			}
14677 
14678 			if (bp == immed_bp) {
14679 				/* immed_bp is gone by now, so clear this */
14680 				immed_bp = NULL;
14681 			}
14682 			break;
14683 		}
14684 
14685 	} while (immed_bp == NULL);
14686 
14687 exit:
14688 	ASSERT(mutex_owned(SD_MUTEX(un)));
14689 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
14690 }
14691 
14692 
14693 /*
14694  *    Function: sd_return_command
14695  *
14696  * Description: Returns a command to its originator (with or without an
14697  *		error).  Also starts commands waiting to be transported
14698  *		to the target.
14699  *
14700  *     Context: May be called from interrupt, kernel, or timeout context
14701  */
14702 
14703 static void
14704 sd_return_command(struct sd_lun *un, struct buf *bp)
14705 {
14706 	struct sd_xbuf *xp;
14707 #if defined(__i386) || defined(__amd64)
14708 	struct scsi_pkt *pktp;
14709 #endif
14710 
14711 	ASSERT(bp != NULL);
14712 	ASSERT(un != NULL);
14713 	ASSERT(mutex_owned(SD_MUTEX(un)));
14714 	ASSERT(bp != un->un_rqs_bp);
14715 	xp = SD_GET_XBUF(bp);
14716 	ASSERT(xp != NULL);
14717 
14718 #if defined(__i386) || defined(__amd64)
14719 	pktp = SD_GET_PKTP(bp);
14720 #endif
14721 
14722 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
14723 
14724 #if defined(__i386) || defined(__amd64)
14725 	/*
14726 	 * Note:x86: check for the "sdrestart failed" case.
14727 	 */
14728 	if (((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
14729 		(geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
14730 		(xp->xb_pktp->pkt_resid == 0)) {
14731 
14732 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
14733 			/*
14734 			 * Successfully set up next portion of cmd
14735 			 * transfer, try sending it
14736 			 */
14737 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14738 			    NULL, NULL, 0, (clock_t)0, NULL);
14739 			sd_start_cmds(un, NULL);
14740 			return;	/* Note:x86: need a return here? */
14741 		}
14742 	}
14743 #endif
14744 
14745 	/*
14746 	 * If this is the failfast bp, clear it from un_failfast_bp. This
14747 	 * can happen if upon being re-tried the failfast bp either
14748 	 * succeeded or encountered another error (possibly even a different
14749 	 * error than the one that precipitated the failfast state, but in
14750 	 * that case it would have had to exhaust retries as well). Regardless,
14751 	 * this should not occur whenever the instance is in the active
14752 	 * failfast state.
14753 	 */
14754 	if (bp == un->un_failfast_bp) {
14755 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
14756 		un->un_failfast_bp = NULL;
14757 	}
14758 
14759 	/*
14760 	 * Clear the failfast state upon successful completion of ANY cmd.
14761 	 */
14762 	if (bp->b_error == 0) {
14763 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
14764 	}
14765 
14766 	/*
14767 	 * This is used if the command was retried one or more times. Show that
14768 	 * we are done with it, and allow processing of the waitq to resume.
14769 	 */
14770 	if (bp == un->un_retry_bp) {
14771 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14772 		    "sd_return_command: un:0x%p: "
14773 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
14774 		un->un_retry_bp = NULL;
14775 		un->un_retry_statp = NULL;
14776 	}
14777 
14778 	SD_UPDATE_RDWR_STATS(un, bp);
14779 	SD_UPDATE_PARTITION_STATS(un, bp);
14780 
14781 	switch (un->un_state) {
14782 	case SD_STATE_SUSPENDED:
14783 		/*
14784 		 * Notify any threads waiting in sd_ddi_suspend() that
14785 		 * a command completion has occurred.
14786 		 */
14787 		cv_broadcast(&un->un_disk_busy_cv);
14788 		break;
14789 	default:
14790 		sd_start_cmds(un, NULL);
14791 		break;
14792 	}
14793 
14794 	/* Return this command up the iodone chain to its originator. */
14795 	mutex_exit(SD_MUTEX(un));
14796 
14797 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
14798 	xp->xb_pktp = NULL;
14799 
14800 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
14801 
14802 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14803 	mutex_enter(SD_MUTEX(un));
14804 
14805 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
14806 }
14807 
14808 
14809 /*
14810  *    Function: sd_return_failed_command
14811  *
14812  * Description: Command completion when an error occurred.
14813  *
14814  *     Context: May be called from interrupt context
14815  */
14816 
14817 static void
14818 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
14819 {
14820 	ASSERT(bp != NULL);
14821 	ASSERT(un != NULL);
14822 	ASSERT(mutex_owned(SD_MUTEX(un)));
14823 
14824 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14825 	    "sd_return_failed_command: entry\n");
14826 
14827 	/*
14828 	 * b_resid could already be nonzero due to a partial data
14829 	 * transfer, so do not change it here.
14830 	 */
14831 	SD_BIOERROR(bp, errcode);
14832 
14833 	sd_return_command(un, bp);
14834 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14835 	    "sd_return_failed_command: exit\n");
14836 }
14837 
14838 
14839 /*
14840  *    Function: sd_return_failed_command_no_restart
14841  *
14842  * Description: Same as sd_return_failed_command, but ensures that no
14843  *		call back into sd_start_cmds will be issued.
14844  *
14845  *     Context: May be called from interrupt context
14846  */
14847 
14848 static void
14849 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
14850 	int errcode)
14851 {
14852 	struct sd_xbuf *xp;
14853 
14854 	ASSERT(bp != NULL);
14855 	ASSERT(un != NULL);
14856 	ASSERT(mutex_owned(SD_MUTEX(un)));
14857 	xp = SD_GET_XBUF(bp);
14858 	ASSERT(xp != NULL);
14859 	ASSERT(errcode != 0);
14860 
14861 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14862 	    "sd_return_failed_command_no_restart: entry\n");
14863 
14864 	/*
14865 	 * b_resid could already be nonzero due to a partial data
14866 	 * transfer, so do not change it here.
14867 	 */
14868 	SD_BIOERROR(bp, errcode);
14869 
14870 	/*
14871 	 * If this is the failfast bp, clear it. This can happen if the
14872 	 * failfast bp encounterd a fatal error when we attempted to
14873 	 * re-try it (such as a scsi_transport(9F) failure).  However
14874 	 * we should NOT be in an active failfast state if the failfast
14875 	 * bp is not NULL.
14876 	 */
14877 	if (bp == un->un_failfast_bp) {
14878 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
14879 		un->un_failfast_bp = NULL;
14880 	}
14881 
14882 	if (bp == un->un_retry_bp) {
14883 		/*
14884 		 * This command was retried one or more times. Show that we are
14885 		 * done with it, and allow processing of the waitq to resume.
14886 		 */
14887 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14888 		    "sd_return_failed_command_no_restart: "
14889 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
14890 		un->un_retry_bp = NULL;
14891 		un->un_retry_statp = NULL;
14892 	}
14893 
14894 	SD_UPDATE_RDWR_STATS(un, bp);
14895 	SD_UPDATE_PARTITION_STATS(un, bp);
14896 
14897 	mutex_exit(SD_MUTEX(un));
14898 
14899 	if (xp->xb_pktp != NULL) {
14900 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
14901 		xp->xb_pktp = NULL;
14902 	}
14903 
14904 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
14905 
14906 	mutex_enter(SD_MUTEX(un));
14907 
14908 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14909 	    "sd_return_failed_command_no_restart: exit\n");
14910 }
14911 
14912 
14913 /*
14914  *    Function: sd_retry_command
14915  *
14916  * Description: queue up a command for retry, or (optionally) fail it
14917  *		if retry counts are exhausted.
14918  *
14919  *   Arguments: un - Pointer to the sd_lun struct for the target.
14920  *
14921  *		bp - Pointer to the buf for the command to be retried.
14922  *
14923  *		retry_check_flag - Flag to see which (if any) of the retry
14924  *		   counts should be decremented/checked. If the indicated
14925  *		   retry count is exhausted, then the command will not be
14926  *		   retried; it will be failed instead. This should use a
14927  *		   value equal to one of the following:
14928  *
14929  *			SD_RETRIES_NOCHECK
14930  *			SD_RESD_RETRIES_STANDARD
14931  *			SD_RETRIES_VICTIM
14932  *
14933  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
14934  *		   if the check should be made to see of FLAG_ISOLATE is set
14935  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
14936  *		   not retried, it is simply failed.
14937  *
14938  *		user_funcp - Ptr to function to call before dispatching the
14939  *		   command. May be NULL if no action needs to be performed.
14940  *		   (Primarily intended for printing messages.)
14941  *
14942  *		user_arg - Optional argument to be passed along to
14943  *		   the user_funcp call.
14944  *
14945  *		failure_code - errno return code to set in the bp if the
14946  *		   command is going to be failed.
14947  *
14948  *		retry_delay - Retry delay interval in (clock_t) units. May
14949  *		   be zero which indicates that the retry should be retried
14950  *		   immediately (ie, without an intervening delay).
14951  *
14952  *		statp - Ptr to kstat function to be updated if the command
14953  *		   is queued for a delayed retry. May be NULL if no kstat
14954  *		   update is desired.
14955  *
14956  *     Context: May be called from interupt context.
14957  */
14958 
14959 static void
14960 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
14961 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
14962 	code), void *user_arg, int failure_code,  clock_t retry_delay,
14963 	void (*statp)(kstat_io_t *))
14964 {
14965 	struct sd_xbuf	*xp;
14966 	struct scsi_pkt	*pktp;
14967 
14968 	ASSERT(un != NULL);
14969 	ASSERT(mutex_owned(SD_MUTEX(un)));
14970 	ASSERT(bp != NULL);
14971 	xp = SD_GET_XBUF(bp);
14972 	ASSERT(xp != NULL);
14973 	pktp = SD_GET_PKTP(bp);
14974 	ASSERT(pktp != NULL);
14975 
14976 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14977 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
14978 
14979 	/*
14980 	 * If we are syncing or dumping, fail the command to avoid
14981 	 * recursively calling back into scsi_transport().
14982 	 */
14983 	if (ddi_in_panic()) {
14984 		goto fail_command_no_log;
14985 	}
14986 
14987 	/*
14988 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
14989 	 * log an error and fail the command.
14990 	 */
14991 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14992 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
14993 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
14994 		sd_dump_memory(un, SD_LOG_IO, "CDB",
14995 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
14996 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
14997 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
14998 		goto fail_command;
14999 	}
15000 
15001 	/*
15002 	 * If we are suspended, then put the command onto head of the
15003 	 * wait queue since we don't want to start more commands.
15004 	 */
15005 	switch (un->un_state) {
15006 	case SD_STATE_SUSPENDED:
15007 	case SD_STATE_DUMPING:
15008 		bp->av_forw = un->un_waitq_headp;
15009 		un->un_waitq_headp = bp;
15010 		if (un->un_waitq_tailp == NULL) {
15011 			un->un_waitq_tailp = bp;
15012 		}
15013 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15014 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15015 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15016 		return;
15017 	default:
15018 		break;
15019 	}
15020 
15021 	/*
15022 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15023 	 * is set; if it is then we do not want to retry the command.
15024 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15025 	 */
15026 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15027 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15028 			goto fail_command;
15029 		}
15030 	}
15031 
15032 
15033 	/*
15034 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15035 	 * command timeout or a selection timeout has occurred. This means
15036 	 * that we were unable to establish an kind of communication with
15037 	 * the target, and subsequent retries and/or commands are likely
15038 	 * to encounter similar results and take a long time to complete.
15039 	 *
15040 	 * If this is a failfast error condition, we need to update the
15041 	 * failfast state, even if this bp does not have B_FAILFAST set.
15042 	 */
15043 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15044 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15045 			ASSERT(un->un_failfast_bp == NULL);
15046 			/*
15047 			 * If we are already in the active failfast state, and
15048 			 * another failfast error condition has been detected,
15049 			 * then fail this command if it has B_FAILFAST set.
15050 			 * If B_FAILFAST is clear, then maintain the legacy
15051 			 * behavior of retrying heroically, even tho this will
15052 			 * take a lot more time to fail the command.
15053 			 */
15054 			if (bp->b_flags & B_FAILFAST) {
15055 				goto fail_command;
15056 			}
15057 		} else {
15058 			/*
15059 			 * We're not in the active failfast state, but we
15060 			 * have a failfast error condition, so we must begin
15061 			 * transition to the next state. We do this regardless
15062 			 * of whether or not this bp has B_FAILFAST set.
15063 			 */
15064 			if (un->un_failfast_bp == NULL) {
15065 				/*
15066 				 * This is the first bp to meet a failfast
15067 				 * condition so save it on un_failfast_bp &
15068 				 * do normal retry processing. Do not enter
15069 				 * active failfast state yet. This marks
15070 				 * entry into the "failfast pending" state.
15071 				 */
15072 				un->un_failfast_bp = bp;
15073 
15074 			} else if (un->un_failfast_bp == bp) {
15075 				/*
15076 				 * This is the second time *this* bp has
15077 				 * encountered a failfast error condition,
15078 				 * so enter active failfast state & flush
15079 				 * queues as appropriate.
15080 				 */
15081 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15082 				un->un_failfast_bp = NULL;
15083 				sd_failfast_flushq(un);
15084 
15085 				/*
15086 				 * Fail this bp now if B_FAILFAST set;
15087 				 * otherwise continue with retries. (It would
15088 				 * be pretty ironic if this bp succeeded on a
15089 				 * subsequent retry after we just flushed all
15090 				 * the queues).
15091 				 */
15092 				if (bp->b_flags & B_FAILFAST) {
15093 					goto fail_command;
15094 				}
15095 
15096 #if !defined(lint) && !defined(__lint)
15097 			} else {
15098 				/*
15099 				 * If neither of the preceeding conditionals
15100 				 * was true, it means that there is some
15101 				 * *other* bp that has met an inital failfast
15102 				 * condition and is currently either being
15103 				 * retried or is waiting to be retried. In
15104 				 * that case we should perform normal retry
15105 				 * processing on *this* bp, since there is a
15106 				 * chance that the current failfast condition
15107 				 * is transient and recoverable. If that does
15108 				 * not turn out to be the case, then retries
15109 				 * will be cleared when the wait queue is
15110 				 * flushed anyway.
15111 				 */
15112 #endif
15113 			}
15114 		}
15115 	} else {
15116 		/*
15117 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15118 		 * likely were able to at least establish some level of
15119 		 * communication with the target and subsequent commands
15120 		 * and/or retries are likely to get through to the target,
15121 		 * In this case we want to be aggressive about clearing
15122 		 * the failfast state. Note that this does not affect
15123 		 * the "failfast pending" condition.
15124 		 */
15125 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15126 	}
15127 
15128 
15129 	/*
15130 	 * Check the specified retry count to see if we can still do
15131 	 * any retries with this pkt before we should fail it.
15132 	 */
15133 	switch (retry_check_flag & SD_RETRIES_MASK) {
15134 	case SD_RETRIES_VICTIM:
15135 		/*
15136 		 * Check the victim retry count. If exhausted, then fall
15137 		 * thru & check against the standard retry count.
15138 		 */
15139 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15140 			/* Increment count & proceed with the retry */
15141 			xp->xb_victim_retry_count++;
15142 			break;
15143 		}
15144 		/* Victim retries exhausted, fall back to std. retries... */
15145 		/* FALLTHRU */
15146 
15147 	case SD_RETRIES_STANDARD:
15148 		if (xp->xb_retry_count >= un->un_retry_count) {
15149 			/* Retries exhausted, fail the command */
15150 			SD_TRACE(SD_LOG_IO_CORE, un,
15151 			    "sd_retry_command: retries exhausted!\n");
15152 			/*
15153 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15154 			 * commands with nonzero pkt_resid.
15155 			 */
15156 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15157 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15158 			    (pktp->pkt_resid != 0)) {
15159 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15160 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15161 					SD_UPDATE_B_RESID(bp, pktp);
15162 				}
15163 			}
15164 			goto fail_command;
15165 		}
15166 		xp->xb_retry_count++;
15167 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15168 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15169 		break;
15170 
15171 	case SD_RETRIES_UA:
15172 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15173 			/* Retries exhausted, fail the command */
15174 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15175 			    "Unit Attention retries exhausted. "
15176 			    "Check the target.\n");
15177 			goto fail_command;
15178 		}
15179 		xp->xb_ua_retry_count++;
15180 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15181 		    "sd_retry_command: retry count:%d\n",
15182 			xp->xb_ua_retry_count);
15183 		break;
15184 
15185 	case SD_RETRIES_BUSY:
15186 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15187 			/* Retries exhausted, fail the command */
15188 			SD_TRACE(SD_LOG_IO_CORE, un,
15189 			    "sd_retry_command: retries exhausted!\n");
15190 			goto fail_command;
15191 		}
15192 		xp->xb_retry_count++;
15193 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15194 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15195 		break;
15196 
15197 	case SD_RETRIES_NOCHECK:
15198 	default:
15199 		/* No retry count to check. Just proceed with the retry */
15200 		break;
15201 	}
15202 
15203 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15204 
15205 	/*
15206 	 * If we were given a zero timeout, we must attempt to retry the
15207 	 * command immediately (ie, without a delay).
15208 	 */
15209 	if (retry_delay == 0) {
15210 		/*
15211 		 * Check some limiting conditions to see if we can actually
15212 		 * do the immediate retry.  If we cannot, then we must
15213 		 * fall back to queueing up a delayed retry.
15214 		 */
15215 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15216 			/*
15217 			 * We are at the throttle limit for the target,
15218 			 * fall back to delayed retry.
15219 			 */
15220 			retry_delay = SD_BSY_TIMEOUT;
15221 			statp = kstat_waitq_enter;
15222 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15223 			    "sd_retry_command: immed. retry hit "
15224 			    "throttle!\n");
15225 		} else {
15226 			/*
15227 			 * We're clear to proceed with the immediate retry.
15228 			 * First call the user-provided function (if any)
15229 			 */
15230 			if (user_funcp != NULL) {
15231 				(*user_funcp)(un, bp, user_arg,
15232 				    SD_IMMEDIATE_RETRY_ISSUED);
15233 #ifdef __lock_lint
15234 				sd_print_incomplete_msg(un, bp, user_arg,
15235 				    SD_IMMEDIATE_RETRY_ISSUED);
15236 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15237 				    SD_IMMEDIATE_RETRY_ISSUED);
15238 				sd_print_sense_failed_msg(un, bp, user_arg,
15239 				    SD_IMMEDIATE_RETRY_ISSUED);
15240 #endif
15241 			}
15242 
15243 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15244 			    "sd_retry_command: issuing immediate retry\n");
15245 
15246 			/*
15247 			 * Call sd_start_cmds() to transport the command to
15248 			 * the target.
15249 			 */
15250 			sd_start_cmds(un, bp);
15251 
15252 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15253 			    "sd_retry_command exit\n");
15254 			return;
15255 		}
15256 	}
15257 
15258 	/*
15259 	 * Set up to retry the command after a delay.
15260 	 * First call the user-provided function (if any)
15261 	 */
15262 	if (user_funcp != NULL) {
15263 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15264 	}
15265 
15266 	sd_set_retry_bp(un, bp, retry_delay, statp);
15267 
15268 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15269 	return;
15270 
15271 fail_command:
15272 
15273 	if (user_funcp != NULL) {
15274 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15275 	}
15276 
15277 fail_command_no_log:
15278 
15279 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15280 	    "sd_retry_command: returning failed command\n");
15281 
15282 	sd_return_failed_command(un, bp, failure_code);
15283 
15284 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15285 }
15286 
15287 
15288 /*
15289  *    Function: sd_set_retry_bp
15290  *
15291  * Description: Set up the given bp for retry.
15292  *
15293  *   Arguments: un - ptr to associated softstate
15294  *		bp - ptr to buf(9S) for the command
15295  *		retry_delay - time interval before issuing retry (may be 0)
15296  *		statp - optional pointer to kstat function
15297  *
15298  *     Context: May be called under interrupt context
15299  */
15300 
15301 static void
15302 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15303 	void (*statp)(kstat_io_t *))
15304 {
15305 	ASSERT(un != NULL);
15306 	ASSERT(mutex_owned(SD_MUTEX(un)));
15307 	ASSERT(bp != NULL);
15308 
15309 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15310 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15311 
15312 	/*
15313 	 * Indicate that the command is being retried. This will not allow any
15314 	 * other commands on the wait queue to be transported to the target
15315 	 * until this command has been completed (success or failure). The
15316 	 * "retry command" is not transported to the target until the given
15317 	 * time delay expires, unless the user specified a 0 retry_delay.
15318 	 *
15319 	 * Note: the timeout(9F) callback routine is what actually calls
15320 	 * sd_start_cmds() to transport the command, with the exception of a
15321 	 * zero retry_delay. The only current implementor of a zero retry delay
15322 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
15323 	 */
15324 	if (un->un_retry_bp == NULL) {
15325 		ASSERT(un->un_retry_statp == NULL);
15326 		un->un_retry_bp = bp;
15327 
15328 		/*
15329 		 * If the user has not specified a delay the command should
15330 		 * be queued and no timeout should be scheduled.
15331 		 */
15332 		if (retry_delay == 0) {
15333 			/*
15334 			 * Save the kstat pointer that will be used in the
15335 			 * call to SD_UPDATE_KSTATS() below, so that
15336 			 * sd_start_cmds() can correctly decrement the waitq
15337 			 * count when it is time to transport this command.
15338 			 */
15339 			un->un_retry_statp = statp;
15340 			goto done;
15341 		}
15342 	}
15343 
15344 	if (un->un_retry_bp == bp) {
15345 		/*
15346 		 * Save the kstat pointer that will be used in the call to
15347 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
15348 		 * correctly decrement the waitq count when it is time to
15349 		 * transport this command.
15350 		 */
15351 		un->un_retry_statp = statp;
15352 
15353 		/*
15354 		 * Schedule a timeout if:
15355 		 *   1) The user has specified a delay.
15356 		 *   2) There is not a START_STOP_UNIT callback pending.
15357 		 *
15358 		 * If no delay has been specified, then it is up to the caller
15359 		 * to ensure that IO processing continues without stalling.
15360 		 * Effectively, this means that the caller will issue the
15361 		 * required call to sd_start_cmds(). The START_STOP_UNIT
15362 		 * callback does this after the START STOP UNIT command has
15363 		 * completed. In either of these cases we should not schedule
15364 		 * a timeout callback here.  Also don't schedule the timeout if
15365 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
15366 		 */
15367 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
15368 		    (un->un_direct_priority_timeid == NULL)) {
15369 			un->un_retry_timeid =
15370 			    timeout(sd_start_retry_command, un, retry_delay);
15371 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15372 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
15373 			    " bp:0x%p un_retry_timeid:0x%p\n",
15374 			    un, bp, un->un_retry_timeid);
15375 		}
15376 	} else {
15377 		/*
15378 		 * We only get in here if there is already another command
15379 		 * waiting to be retried.  In this case, we just put the
15380 		 * given command onto the wait queue, so it can be transported
15381 		 * after the current retry command has completed.
15382 		 *
15383 		 * Also we have to make sure that if the command at the head
15384 		 * of the wait queue is the un_failfast_bp, that we do not
15385 		 * put ahead of it any other commands that are to be retried.
15386 		 */
15387 		if ((un->un_failfast_bp != NULL) &&
15388 		    (un->un_failfast_bp == un->un_waitq_headp)) {
15389 			/*
15390 			 * Enqueue this command AFTER the first command on
15391 			 * the wait queue (which is also un_failfast_bp).
15392 			 */
15393 			bp->av_forw = un->un_waitq_headp->av_forw;
15394 			un->un_waitq_headp->av_forw = bp;
15395 			if (un->un_waitq_headp == un->un_waitq_tailp) {
15396 				un->un_waitq_tailp = bp;
15397 			}
15398 		} else {
15399 			/* Enqueue this command at the head of the waitq. */
15400 			bp->av_forw = un->un_waitq_headp;
15401 			un->un_waitq_headp = bp;
15402 			if (un->un_waitq_tailp == NULL) {
15403 				un->un_waitq_tailp = bp;
15404 			}
15405 		}
15406 
15407 		if (statp == NULL) {
15408 			statp = kstat_waitq_enter;
15409 		}
15410 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15411 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
15412 	}
15413 
15414 done:
15415 	if (statp != NULL) {
15416 		SD_UPDATE_KSTATS(un, statp, bp);
15417 	}
15418 
15419 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15420 	    "sd_set_retry_bp: exit un:0x%p\n", un);
15421 }
15422 
15423 
15424 /*
15425  *    Function: sd_start_retry_command
15426  *
15427  * Description: Start the command that has been waiting on the target's
15428  *		retry queue.  Called from timeout(9F) context after the
15429  *		retry delay interval has expired.
15430  *
15431  *   Arguments: arg - pointer to associated softstate for the device.
15432  *
15433  *     Context: timeout(9F) thread context.  May not sleep.
15434  */
15435 
15436 static void
15437 sd_start_retry_command(void *arg)
15438 {
15439 	struct sd_lun *un = arg;
15440 
15441 	ASSERT(un != NULL);
15442 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15443 
15444 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15445 	    "sd_start_retry_command: entry\n");
15446 
15447 	mutex_enter(SD_MUTEX(un));
15448 
15449 	un->un_retry_timeid = NULL;
15450 
15451 	if (un->un_retry_bp != NULL) {
15452 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15453 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
15454 		    un, un->un_retry_bp);
15455 		sd_start_cmds(un, un->un_retry_bp);
15456 	}
15457 
15458 	mutex_exit(SD_MUTEX(un));
15459 
15460 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15461 	    "sd_start_retry_command: exit\n");
15462 }
15463 
15464 
15465 /*
15466  *    Function: sd_start_direct_priority_command
15467  *
15468  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
15469  *		received TRAN_BUSY when we called scsi_transport() to send it
15470  *		to the underlying HBA. This function is called from timeout(9F)
15471  *		context after the delay interval has expired.
15472  *
15473  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
15474  *
15475  *     Context: timeout(9F) thread context.  May not sleep.
15476  */
15477 
15478 static void
15479 sd_start_direct_priority_command(void *arg)
15480 {
15481 	struct buf	*priority_bp = arg;
15482 	struct sd_lun	*un;
15483 
15484 	ASSERT(priority_bp != NULL);
15485 	un = SD_GET_UN(priority_bp);
15486 	ASSERT(un != NULL);
15487 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15488 
15489 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15490 	    "sd_start_direct_priority_command: entry\n");
15491 
15492 	mutex_enter(SD_MUTEX(un));
15493 	un->un_direct_priority_timeid = NULL;
15494 	sd_start_cmds(un, priority_bp);
15495 	mutex_exit(SD_MUTEX(un));
15496 
15497 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15498 	    "sd_start_direct_priority_command: exit\n");
15499 }
15500 
15501 
15502 /*
15503  *    Function: sd_send_request_sense_command
15504  *
15505  * Description: Sends a REQUEST SENSE command to the target
15506  *
15507  *     Context: May be called from interrupt context.
15508  */
15509 
15510 static void
15511 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
15512 	struct scsi_pkt *pktp)
15513 {
15514 	ASSERT(bp != NULL);
15515 	ASSERT(un != NULL);
15516 	ASSERT(mutex_owned(SD_MUTEX(un)));
15517 
15518 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
15519 	    "entry: buf:0x%p\n", bp);
15520 
15521 	/*
15522 	 * If we are syncing or dumping, then fail the command to avoid a
15523 	 * recursive callback into scsi_transport(). Also fail the command
15524 	 * if we are suspended (legacy behavior).
15525 	 */
15526 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
15527 	    (un->un_state == SD_STATE_DUMPING)) {
15528 		sd_return_failed_command(un, bp, EIO);
15529 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15530 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
15531 		return;
15532 	}
15533 
15534 	/*
15535 	 * Retry the failed command and don't issue the request sense if:
15536 	 *    1) the sense buf is busy
15537 	 *    2) we have 1 or more outstanding commands on the target
15538 	 *    (the sense data will be cleared or invalidated any way)
15539 	 *
15540 	 * Note: There could be an issue with not checking a retry limit here,
15541 	 * the problem is determining which retry limit to check.
15542 	 */
15543 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
15544 		/* Don't retry if the command is flagged as non-retryable */
15545 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15546 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15547 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
15548 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15549 			    "sd_send_request_sense_command: "
15550 			    "at full throttle, retrying exit\n");
15551 		} else {
15552 			sd_return_failed_command(un, bp, EIO);
15553 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15554 			    "sd_send_request_sense_command: "
15555 			    "at full throttle, non-retryable exit\n");
15556 		}
15557 		return;
15558 	}
15559 
15560 	sd_mark_rqs_busy(un, bp);
15561 	sd_start_cmds(un, un->un_rqs_bp);
15562 
15563 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15564 	    "sd_send_request_sense_command: exit\n");
15565 }
15566 
15567 
15568 /*
15569  *    Function: sd_mark_rqs_busy
15570  *
15571  * Description: Indicate that the request sense bp for this instance is
15572  *		in use.
15573  *
15574  *     Context: May be called under interrupt context
15575  */
15576 
15577 static void
15578 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
15579 {
15580 	struct sd_xbuf	*sense_xp;
15581 
15582 	ASSERT(un != NULL);
15583 	ASSERT(bp != NULL);
15584 	ASSERT(mutex_owned(SD_MUTEX(un)));
15585 	ASSERT(un->un_sense_isbusy == 0);
15586 
15587 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
15588 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
15589 
15590 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
15591 	ASSERT(sense_xp != NULL);
15592 
15593 	SD_INFO(SD_LOG_IO, un,
15594 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
15595 
15596 	ASSERT(sense_xp->xb_pktp != NULL);
15597 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
15598 	    == (FLAG_SENSING | FLAG_HEAD));
15599 
15600 	un->un_sense_isbusy = 1;
15601 	un->un_rqs_bp->b_resid = 0;
15602 	sense_xp->xb_pktp->pkt_resid  = 0;
15603 	sense_xp->xb_pktp->pkt_reason = 0;
15604 
15605 	/* So we can get back the bp at interrupt time! */
15606 	sense_xp->xb_sense_bp = bp;
15607 
15608 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
15609 
15610 	/*
15611 	 * Mark this buf as awaiting sense data. (This is already set in
15612 	 * the pkt_flags for the RQS packet.)
15613 	 */
15614 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
15615 
15616 	sense_xp->xb_retry_count	= 0;
15617 	sense_xp->xb_victim_retry_count = 0;
15618 	sense_xp->xb_ua_retry_count	= 0;
15619 	sense_xp->xb_dma_resid  = 0;
15620 
15621 	/* Clean up the fields for auto-request sense */
15622 	sense_xp->xb_sense_status = 0;
15623 	sense_xp->xb_sense_state  = 0;
15624 	sense_xp->xb_sense_resid  = 0;
15625 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
15626 
15627 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
15628 }
15629 
15630 
15631 /*
15632  *    Function: sd_mark_rqs_idle
15633  *
15634  * Description: SD_MUTEX must be held continuously through this routine
15635  *		to prevent reuse of the rqs struct before the caller can
15636  *		complete it's processing.
15637  *
15638  * Return Code: Pointer to the RQS buf
15639  *
15640  *     Context: May be called under interrupt context
15641  */
15642 
15643 static struct buf *
15644 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
15645 {
15646 	struct buf *bp;
15647 	ASSERT(un != NULL);
15648 	ASSERT(sense_xp != NULL);
15649 	ASSERT(mutex_owned(SD_MUTEX(un)));
15650 	ASSERT(un->un_sense_isbusy != 0);
15651 
15652 	un->un_sense_isbusy = 0;
15653 	bp = sense_xp->xb_sense_bp;
15654 	sense_xp->xb_sense_bp = NULL;
15655 
15656 	/* This pkt is no longer interested in getting sense data */
15657 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
15658 
15659 	return (bp);
15660 }
15661 
15662 
15663 
15664 /*
15665  *    Function: sd_alloc_rqs
15666  *
15667  * Description: Set up the unit to receive auto request sense data
15668  *
15669  * Return Code: DDI_SUCCESS or DDI_FAILURE
15670  *
15671  *     Context: Called under attach(9E) context
15672  */
15673 
15674 static int
15675 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
15676 {
15677 	struct sd_xbuf *xp;
15678 
15679 	ASSERT(un != NULL);
15680 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15681 	ASSERT(un->un_rqs_bp == NULL);
15682 	ASSERT(un->un_rqs_pktp == NULL);
15683 
15684 	/*
15685 	 * First allocate the required buf and scsi_pkt structs, then set up
15686 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
15687 	 */
15688 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
15689 	    SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
15690 	if (un->un_rqs_bp == NULL) {
15691 		return (DDI_FAILURE);
15692 	}
15693 
15694 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
15695 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
15696 
15697 	if (un->un_rqs_pktp == NULL) {
15698 		sd_free_rqs(un);
15699 		return (DDI_FAILURE);
15700 	}
15701 
15702 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
15703 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
15704 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
15705 
15706 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
15707 
15708 	/* Set up the other needed members in the ARQ scsi_pkt. */
15709 	un->un_rqs_pktp->pkt_comp   = sdintr;
15710 	un->un_rqs_pktp->pkt_time   = sd_io_time;
15711 	un->un_rqs_pktp->pkt_flags |=
15712 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
15713 
15714 	/*
15715 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
15716 	 * provide any intpkt, destroypkt routines as we take care of
15717 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
15718 	 */
15719 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
15720 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
15721 	xp->xb_pktp = un->un_rqs_pktp;
15722 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
15723 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
15724 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
15725 
15726 	/*
15727 	 * Save the pointer to the request sense private bp so it can
15728 	 * be retrieved in sdintr.
15729 	 */
15730 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
15731 	ASSERT(un->un_rqs_bp->b_private == xp);
15732 
15733 	/*
15734 	 * See if the HBA supports auto-request sense for the specified
15735 	 * target/lun. If it does, then try to enable it (if not already
15736 	 * enabled).
15737 	 *
15738 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
15739 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
15740 	 * return success.  However, in both of these cases ARQ is always
15741 	 * enabled and scsi_ifgetcap will always return true. The best approach
15742 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
15743 	 *
15744 	 * The 3rd case is the HBA (adp) always return enabled on
15745 	 * scsi_ifgetgetcap even when it's not enable, the best approach
15746 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
15747 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
15748 	 */
15749 
15750 	if (un->un_f_is_fibre == TRUE) {
15751 		un->un_f_arq_enabled = TRUE;
15752 	} else {
15753 #if defined(__i386) || defined(__amd64)
15754 		/*
15755 		 * Circumvent the Adaptec bug, remove this code when
15756 		 * the bug is fixed
15757 		 */
15758 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
15759 #endif
15760 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
15761 		case 0:
15762 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15763 				"sd_alloc_rqs: HBA supports ARQ\n");
15764 			/*
15765 			 * ARQ is supported by this HBA but currently is not
15766 			 * enabled. Attempt to enable it and if successful then
15767 			 * mark this instance as ARQ enabled.
15768 			 */
15769 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
15770 				== 1) {
15771 				/* Successfully enabled ARQ in the HBA */
15772 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
15773 					"sd_alloc_rqs: ARQ enabled\n");
15774 				un->un_f_arq_enabled = TRUE;
15775 			} else {
15776 				/* Could not enable ARQ in the HBA */
15777 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
15778 				"sd_alloc_rqs: failed ARQ enable\n");
15779 				un->un_f_arq_enabled = FALSE;
15780 			}
15781 			break;
15782 		case 1:
15783 			/*
15784 			 * ARQ is supported by this HBA and is already enabled.
15785 			 * Just mark ARQ as enabled for this instance.
15786 			 */
15787 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15788 				"sd_alloc_rqs: ARQ already enabled\n");
15789 			un->un_f_arq_enabled = TRUE;
15790 			break;
15791 		default:
15792 			/*
15793 			 * ARQ is not supported by this HBA; disable it for this
15794 			 * instance.
15795 			 */
15796 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15797 				"sd_alloc_rqs: HBA does not support ARQ\n");
15798 			un->un_f_arq_enabled = FALSE;
15799 			break;
15800 		}
15801 	}
15802 
15803 	return (DDI_SUCCESS);
15804 }
15805 
15806 
15807 /*
15808  *    Function: sd_free_rqs
15809  *
15810  * Description: Cleanup for the pre-instance RQS command.
15811  *
15812  *     Context: Kernel thread context
15813  */
15814 
15815 static void
15816 sd_free_rqs(struct sd_lun *un)
15817 {
15818 	ASSERT(un != NULL);
15819 
15820 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
15821 
15822 	/*
15823 	 * If consistent memory is bound to a scsi_pkt, the pkt
15824 	 * has to be destroyed *before* freeing the consistent memory.
15825 	 * Don't change the sequence of this operations.
15826 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
15827 	 * after it was freed in scsi_free_consistent_buf().
15828 	 */
15829 	if (un->un_rqs_pktp != NULL) {
15830 		scsi_destroy_pkt(un->un_rqs_pktp);
15831 		un->un_rqs_pktp = NULL;
15832 	}
15833 
15834 	if (un->un_rqs_bp != NULL) {
15835 		kmem_free(SD_GET_XBUF(un->un_rqs_bp), sizeof (struct sd_xbuf));
15836 		scsi_free_consistent_buf(un->un_rqs_bp);
15837 		un->un_rqs_bp = NULL;
15838 	}
15839 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
15840 }
15841 
15842 
15843 
15844 /*
15845  *    Function: sd_reduce_throttle
15846  *
15847  * Description: Reduces the maximun # of outstanding commands on a
15848  *		target to the current number of outstanding commands.
15849  *		Queues a tiemout(9F) callback to restore the limit
15850  *		after a specified interval has elapsed.
15851  *		Typically used when we get a TRAN_BUSY return code
15852  *		back from scsi_transport().
15853  *
15854  *   Arguments: un - ptr to the sd_lun softstate struct
15855  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
15856  *
15857  *     Context: May be called from interrupt context
15858  */
15859 
15860 static void
15861 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
15862 {
15863 	ASSERT(un != NULL);
15864 	ASSERT(mutex_owned(SD_MUTEX(un)));
15865 	ASSERT(un->un_ncmds_in_transport >= 0);
15866 
15867 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
15868 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
15869 	    un, un->un_throttle, un->un_ncmds_in_transport);
15870 
15871 	if (un->un_throttle > 1) {
15872 		if (un->un_f_use_adaptive_throttle == TRUE) {
15873 			switch (throttle_type) {
15874 			case SD_THROTTLE_TRAN_BUSY:
15875 				if (un->un_busy_throttle == 0) {
15876 					un->un_busy_throttle = un->un_throttle;
15877 				}
15878 				break;
15879 			case SD_THROTTLE_QFULL:
15880 				un->un_busy_throttle = 0;
15881 				break;
15882 			default:
15883 				ASSERT(FALSE);
15884 			}
15885 
15886 			if (un->un_ncmds_in_transport > 0) {
15887 			    un->un_throttle = un->un_ncmds_in_transport;
15888 			}
15889 
15890 		} else {
15891 			if (un->un_ncmds_in_transport == 0) {
15892 				un->un_throttle = 1;
15893 			} else {
15894 				un->un_throttle = un->un_ncmds_in_transport;
15895 			}
15896 		}
15897 	}
15898 
15899 	/* Reschedule the timeout if none is currently active */
15900 	if (un->un_reset_throttle_timeid == NULL) {
15901 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
15902 		    un, SD_THROTTLE_RESET_INTERVAL);
15903 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15904 		    "sd_reduce_throttle: timeout scheduled!\n");
15905 	}
15906 
15907 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
15908 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
15909 }
15910 
15911 
15912 
15913 /*
15914  *    Function: sd_restore_throttle
15915  *
15916  * Description: Callback function for timeout(9F).  Resets the current
15917  *		value of un->un_throttle to its default.
15918  *
15919  *   Arguments: arg - pointer to associated softstate for the device.
15920  *
15921  *     Context: May be called from interrupt context
15922  */
15923 
15924 static void
15925 sd_restore_throttle(void *arg)
15926 {
15927 	struct sd_lun	*un = arg;
15928 
15929 	ASSERT(un != NULL);
15930 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15931 
15932 	mutex_enter(SD_MUTEX(un));
15933 
15934 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
15935 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
15936 
15937 	un->un_reset_throttle_timeid = NULL;
15938 
15939 	if (un->un_f_use_adaptive_throttle == TRUE) {
15940 		/*
15941 		 * If un_busy_throttle is nonzero, then it contains the
15942 		 * value that un_throttle was when we got a TRAN_BUSY back
15943 		 * from scsi_transport(). We want to revert back to this
15944 		 * value.
15945 		 *
15946 		 * In the QFULL case, the throttle limit will incrementally
15947 		 * increase until it reaches max throttle.
15948 		 */
15949 		if (un->un_busy_throttle > 0) {
15950 			un->un_throttle = un->un_busy_throttle;
15951 			un->un_busy_throttle = 0;
15952 		} else {
15953 			/*
15954 			 * increase throttle by 10% open gate slowly, schedule
15955 			 * another restore if saved throttle has not been
15956 			 * reached
15957 			 */
15958 			short throttle;
15959 			if (sd_qfull_throttle_enable) {
15960 				throttle = un->un_throttle +
15961 				    max((un->un_throttle / 10), 1);
15962 				un->un_throttle =
15963 				    (throttle < un->un_saved_throttle) ?
15964 				    throttle : un->un_saved_throttle;
15965 				if (un->un_throttle < un->un_saved_throttle) {
15966 				    un->un_reset_throttle_timeid =
15967 					timeout(sd_restore_throttle,
15968 					un, SD_QFULL_THROTTLE_RESET_INTERVAL);
15969 				}
15970 			}
15971 		}
15972 
15973 		/*
15974 		 * If un_throttle has fallen below the low-water mark, we
15975 		 * restore the maximum value here (and allow it to ratchet
15976 		 * down again if necessary).
15977 		 */
15978 		if (un->un_throttle < un->un_min_throttle) {
15979 			un->un_throttle = un->un_saved_throttle;
15980 		}
15981 	} else {
15982 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
15983 		    "restoring limit from 0x%x to 0x%x\n",
15984 		    un->un_throttle, un->un_saved_throttle);
15985 		un->un_throttle = un->un_saved_throttle;
15986 	}
15987 
15988 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15989 	    "sd_restore_throttle: calling sd_start_cmds!\n");
15990 
15991 	sd_start_cmds(un, NULL);
15992 
15993 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15994 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
15995 	    un, un->un_throttle);
15996 
15997 	mutex_exit(SD_MUTEX(un));
15998 
15999 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16000 }
16001 
16002 /*
16003  *    Function: sdrunout
16004  *
16005  * Description: Callback routine for scsi_init_pkt when a resource allocation
16006  *		fails.
16007  *
16008  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16009  *		soft state instance.
16010  *
16011  * Return Code: The scsi_init_pkt routine allows for the callback function to
16012  *		return a 0 indicating the callback should be rescheduled or a 1
16013  *		indicating not to reschedule. This routine always returns 1
16014  *		because the driver always provides a callback function to
16015  *		scsi_init_pkt. This results in a callback always being scheduled
16016  *		(via the scsi_init_pkt callback implementation) if a resource
16017  *		failure occurs.
16018  *
16019  *     Context: This callback function may not block or call routines that block
16020  *
16021  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16022  *		request persisting at the head of the list which cannot be
16023  *		satisfied even after multiple retries. In the future the driver
16024  *		may implement some time of maximum runout count before failing
16025  *		an I/O.
16026  */
16027 
16028 static int
16029 sdrunout(caddr_t arg)
16030 {
16031 	struct sd_lun	*un = (struct sd_lun *)arg;
16032 
16033 	ASSERT(un != NULL);
16034 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16035 
16036 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16037 
16038 	mutex_enter(SD_MUTEX(un));
16039 	sd_start_cmds(un, NULL);
16040 	mutex_exit(SD_MUTEX(un));
16041 	/*
16042 	 * This callback routine always returns 1 (i.e. do not reschedule)
16043 	 * because we always specify sdrunout as the callback handler for
16044 	 * scsi_init_pkt inside the call to sd_start_cmds.
16045 	 */
16046 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16047 	return (1);
16048 }
16049 
16050 
16051 /*
16052  *    Function: sdintr
16053  *
16054  * Description: Completion callback routine for scsi_pkt(9S) structs
16055  *		sent to the HBA driver via scsi_transport(9F).
16056  *
16057  *     Context: Interrupt context
16058  */
16059 
16060 static void
16061 sdintr(struct scsi_pkt *pktp)
16062 {
16063 	struct buf	*bp;
16064 	struct sd_xbuf	*xp;
16065 	struct sd_lun	*un;
16066 
16067 	ASSERT(pktp != NULL);
16068 	bp = (struct buf *)pktp->pkt_private;
16069 	ASSERT(bp != NULL);
16070 	xp = SD_GET_XBUF(bp);
16071 	ASSERT(xp != NULL);
16072 	ASSERT(xp->xb_pktp != NULL);
16073 	un = SD_GET_UN(bp);
16074 	ASSERT(un != NULL);
16075 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16076 
16077 #ifdef SD_FAULT_INJECTION
16078 
16079 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16080 	/* SD FaultInjection */
16081 	sd_faultinjection(pktp);
16082 
16083 #endif /* SD_FAULT_INJECTION */
16084 
16085 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16086 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16087 
16088 	mutex_enter(SD_MUTEX(un));
16089 
16090 	/* Reduce the count of the #commands currently in transport */
16091 	un->un_ncmds_in_transport--;
16092 	ASSERT(un->un_ncmds_in_transport >= 0);
16093 
16094 	/* Increment counter to indicate that the callback routine is active */
16095 	un->un_in_callback++;
16096 
16097 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16098 
16099 #ifdef	SDDEBUG
16100 	if (bp == un->un_retry_bp) {
16101 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16102 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16103 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16104 	}
16105 #endif
16106 
16107 	/*
16108 	 * If pkt_reason is CMD_DEV_GONE, just fail the command
16109 	 */
16110 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16111 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
16112 			    "Device is gone\n");
16113 		sd_return_failed_command(un, bp, EIO);
16114 		goto exit;
16115 	}
16116 
16117 	/*
16118 	 * First see if the pkt has auto-request sense data with it....
16119 	 * Look at the packet state first so we don't take a performance
16120 	 * hit looking at the arq enabled flag unless absolutely necessary.
16121 	 */
16122 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16123 	    (un->un_f_arq_enabled == TRUE)) {
16124 		/*
16125 		 * The HBA did an auto request sense for this command so check
16126 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16127 		 * driver command that should not be retried.
16128 		 */
16129 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16130 			/*
16131 			 * Save the relevant sense info into the xp for the
16132 			 * original cmd.
16133 			 */
16134 			struct scsi_arq_status *asp;
16135 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16136 			xp->xb_sense_status =
16137 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16138 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16139 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16140 			bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16141 			    min(sizeof (struct scsi_extended_sense),
16142 			    SENSE_LENGTH));
16143 
16144 			/* fail the command */
16145 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16146 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16147 			sd_return_failed_command(un, bp, EIO);
16148 			goto exit;
16149 		}
16150 
16151 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16152 		/*
16153 		 * We want to either retry or fail this command, so free
16154 		 * the DMA resources here.  If we retry the command then
16155 		 * the DMA resources will be reallocated in sd_start_cmds().
16156 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16157 		 * causes the *entire* transfer to start over again from the
16158 		 * beginning of the request, even for PARTIAL chunks that
16159 		 * have already transferred successfully.
16160 		 */
16161 		if ((un->un_f_is_fibre == TRUE) &&
16162 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16163 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16164 			scsi_dmafree(pktp);
16165 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16166 		}
16167 #endif
16168 
16169 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16170 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16171 
16172 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16173 		goto exit;
16174 	}
16175 
16176 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16177 	if (pktp->pkt_flags & FLAG_SENSING)  {
16178 		/* This pktp is from the unit's REQUEST_SENSE command */
16179 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16180 		    "sdintr: sd_handle_request_sense\n");
16181 		sd_handle_request_sense(un, bp, xp, pktp);
16182 		goto exit;
16183 	}
16184 
16185 	/*
16186 	 * Check to see if the command successfully completed as requested;
16187 	 * this is the most common case (and also the hot performance path).
16188 	 *
16189 	 * Requirements for successful completion are:
16190 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16191 	 * In addition:
16192 	 * - A residual of zero indicates successful completion no matter what
16193 	 *   the command is.
16194 	 * - If the residual is not zero and the command is not a read or
16195 	 *   write, then it's still defined as successful completion. In other
16196 	 *   words, if the command is a read or write the residual must be
16197 	 *   zero for successful completion.
16198 	 * - If the residual is not zero and the command is a read or
16199 	 *   write, and it's a USCSICMD, then it's still defined as
16200 	 *   successful completion.
16201 	 */
16202 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16203 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16204 
16205 		/*
16206 		 * Since this command is returned with a good status, we
16207 		 * can reset the count for Sonoma failover.
16208 		 */
16209 		un->un_sonoma_failure_count = 0;
16210 
16211 		/*
16212 		 * Return all USCSI commands on good status
16213 		 */
16214 		if (pktp->pkt_resid == 0) {
16215 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16216 			    "sdintr: returning command for resid == 0\n");
16217 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
16218 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
16219 			SD_UPDATE_B_RESID(bp, pktp);
16220 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16221 			    "sdintr: returning command for resid != 0\n");
16222 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16223 			SD_UPDATE_B_RESID(bp, pktp);
16224 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16225 				"sdintr: returning uscsi command\n");
16226 		} else {
16227 			goto not_successful;
16228 		}
16229 		sd_return_command(un, bp);
16230 
16231 		/*
16232 		 * Decrement counter to indicate that the callback routine
16233 		 * is done.
16234 		 */
16235 		un->un_in_callback--;
16236 		ASSERT(un->un_in_callback >= 0);
16237 		mutex_exit(SD_MUTEX(un));
16238 
16239 		return;
16240 	}
16241 
16242 not_successful:
16243 
16244 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16245 	/*
16246 	 * The following is based upon knowledge of the underlying transport
16247 	 * and its use of DMA resources.  This code should be removed when
16248 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
16249 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
16250 	 * and sd_start_cmds().
16251 	 *
16252 	 * Free any DMA resources associated with this command if there
16253 	 * is a chance it could be retried or enqueued for later retry.
16254 	 * If we keep the DMA binding then mpxio cannot reissue the
16255 	 * command on another path whenever a path failure occurs.
16256 	 *
16257 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
16258 	 * causes the *entire* transfer to start over again from the
16259 	 * beginning of the request, even for PARTIAL chunks that
16260 	 * have already transferred successfully.
16261 	 *
16262 	 * This is only done for non-uscsi commands (and also skipped for the
16263 	 * driver's internal RQS command). Also just do this for Fibre Channel
16264 	 * devices as these are the only ones that support mpxio.
16265 	 */
16266 	if ((un->un_f_is_fibre == TRUE) &&
16267 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16268 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16269 		scsi_dmafree(pktp);
16270 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16271 	}
16272 #endif
16273 
16274 	/*
16275 	 * The command did not successfully complete as requested so check
16276 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16277 	 * driver command that should not be retried so just return. If
16278 	 * FLAG_DIAGNOSE is not set the error will be processed below.
16279 	 */
16280 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16281 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16282 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
16283 		/*
16284 		 * Issue a request sense if a check condition caused the error
16285 		 * (we handle the auto request sense case above), otherwise
16286 		 * just fail the command.
16287 		 */
16288 		if ((pktp->pkt_reason == CMD_CMPLT) &&
16289 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
16290 			sd_send_request_sense_command(un, bp, pktp);
16291 		} else {
16292 			sd_return_failed_command(un, bp, EIO);
16293 		}
16294 		goto exit;
16295 	}
16296 
16297 	/*
16298 	 * The command did not successfully complete as requested so process
16299 	 * the error, retry, and/or attempt recovery.
16300 	 */
16301 	switch (pktp->pkt_reason) {
16302 	case CMD_CMPLT:
16303 		switch (SD_GET_PKT_STATUS(pktp)) {
16304 		case STATUS_GOOD:
16305 			/*
16306 			 * The command completed successfully with a non-zero
16307 			 * residual
16308 			 */
16309 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16310 			    "sdintr: STATUS_GOOD \n");
16311 			sd_pkt_status_good(un, bp, xp, pktp);
16312 			break;
16313 
16314 		case STATUS_CHECK:
16315 		case STATUS_TERMINATED:
16316 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16317 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
16318 			sd_pkt_status_check_condition(un, bp, xp, pktp);
16319 			break;
16320 
16321 		case STATUS_BUSY:
16322 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16323 			    "sdintr: STATUS_BUSY\n");
16324 			sd_pkt_status_busy(un, bp, xp, pktp);
16325 			break;
16326 
16327 		case STATUS_RESERVATION_CONFLICT:
16328 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16329 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
16330 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16331 			break;
16332 
16333 		case STATUS_QFULL:
16334 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16335 			    "sdintr: STATUS_QFULL\n");
16336 			sd_pkt_status_qfull(un, bp, xp, pktp);
16337 			break;
16338 
16339 		case STATUS_MET:
16340 		case STATUS_INTERMEDIATE:
16341 		case STATUS_SCSI2:
16342 		case STATUS_INTERMEDIATE_MET:
16343 		case STATUS_ACA_ACTIVE:
16344 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
16345 			    "Unexpected SCSI status received: 0x%x\n",
16346 			    SD_GET_PKT_STATUS(pktp));
16347 			sd_return_failed_command(un, bp, EIO);
16348 			break;
16349 
16350 		default:
16351 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
16352 			    "Invalid SCSI status received: 0x%x\n",
16353 			    SD_GET_PKT_STATUS(pktp));
16354 			sd_return_failed_command(un, bp, EIO);
16355 			break;
16356 
16357 		}
16358 		break;
16359 
16360 	case CMD_INCOMPLETE:
16361 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16362 		    "sdintr:  CMD_INCOMPLETE\n");
16363 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
16364 		break;
16365 	case CMD_TRAN_ERR:
16366 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16367 		    "sdintr: CMD_TRAN_ERR\n");
16368 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
16369 		break;
16370 	case CMD_RESET:
16371 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16372 		    "sdintr: CMD_RESET \n");
16373 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
16374 		break;
16375 	case CMD_ABORTED:
16376 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16377 		    "sdintr: CMD_ABORTED \n");
16378 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
16379 		break;
16380 	case CMD_TIMEOUT:
16381 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16382 		    "sdintr: CMD_TIMEOUT\n");
16383 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
16384 		break;
16385 	case CMD_UNX_BUS_FREE:
16386 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16387 		    "sdintr: CMD_UNX_BUS_FREE \n");
16388 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
16389 		break;
16390 	case CMD_TAG_REJECT:
16391 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16392 		    "sdintr: CMD_TAG_REJECT\n");
16393 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
16394 		break;
16395 	default:
16396 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16397 		    "sdintr: default\n");
16398 		sd_pkt_reason_default(un, bp, xp, pktp);
16399 		break;
16400 	}
16401 
16402 exit:
16403 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
16404 
16405 	/* Decrement counter to indicate that the callback routine is done. */
16406 	un->un_in_callback--;
16407 	ASSERT(un->un_in_callback >= 0);
16408 
16409 	/*
16410 	 * At this point, the pkt has been dispatched, ie, it is either
16411 	 * being re-tried or has been returned to its caller and should
16412 	 * not be referenced.
16413 	 */
16414 
16415 	mutex_exit(SD_MUTEX(un));
16416 }
16417 
16418 
16419 /*
16420  *    Function: sd_print_incomplete_msg
16421  *
16422  * Description: Prints the error message for a CMD_INCOMPLETE error.
16423  *
16424  *   Arguments: un - ptr to associated softstate for the device.
16425  *		bp - ptr to the buf(9S) for the command.
16426  *		arg - message string ptr
16427  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
16428  *			or SD_NO_RETRY_ISSUED.
16429  *
16430  *     Context: May be called under interrupt context
16431  */
16432 
16433 static void
16434 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
16435 {
16436 	struct scsi_pkt	*pktp;
16437 	char	*msgp;
16438 	char	*cmdp = arg;
16439 
16440 	ASSERT(un != NULL);
16441 	ASSERT(mutex_owned(SD_MUTEX(un)));
16442 	ASSERT(bp != NULL);
16443 	ASSERT(arg != NULL);
16444 	pktp = SD_GET_PKTP(bp);
16445 	ASSERT(pktp != NULL);
16446 
16447 	switch (code) {
16448 	case SD_DELAYED_RETRY_ISSUED:
16449 	case SD_IMMEDIATE_RETRY_ISSUED:
16450 		msgp = "retrying";
16451 		break;
16452 	case SD_NO_RETRY_ISSUED:
16453 	default:
16454 		msgp = "giving up";
16455 		break;
16456 	}
16457 
16458 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16459 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16460 		    "incomplete %s- %s\n", cmdp, msgp);
16461 	}
16462 }
16463 
16464 
16465 
16466 /*
16467  *    Function: sd_pkt_status_good
16468  *
16469  * Description: Processing for a STATUS_GOOD code in pkt_status.
16470  *
16471  *     Context: May be called under interrupt context
16472  */
16473 
16474 static void
16475 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
16476 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16477 {
16478 	char	*cmdp;
16479 
16480 	ASSERT(un != NULL);
16481 	ASSERT(mutex_owned(SD_MUTEX(un)));
16482 	ASSERT(bp != NULL);
16483 	ASSERT(xp != NULL);
16484 	ASSERT(pktp != NULL);
16485 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
16486 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
16487 	ASSERT(pktp->pkt_resid != 0);
16488 
16489 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
16490 
16491 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16492 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
16493 	case SCMD_READ:
16494 		cmdp = "read";
16495 		break;
16496 	case SCMD_WRITE:
16497 		cmdp = "write";
16498 		break;
16499 	default:
16500 		SD_UPDATE_B_RESID(bp, pktp);
16501 		sd_return_command(un, bp);
16502 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
16503 		return;
16504 	}
16505 
16506 	/*
16507 	 * See if we can retry the read/write, preferrably immediately.
16508 	 * If retries are exhaused, then sd_retry_command() will update
16509 	 * the b_resid count.
16510 	 */
16511 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
16512 	    cmdp, EIO, (clock_t)0, NULL);
16513 
16514 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
16515 }
16516 
16517 
16518 
16519 
16520 
16521 /*
16522  *    Function: sd_handle_request_sense
16523  *
16524  * Description: Processing for non-auto Request Sense command.
16525  *
16526  *   Arguments: un - ptr to associated softstate
16527  *		sense_bp - ptr to buf(9S) for the RQS command
16528  *		sense_xp - ptr to the sd_xbuf for the RQS command
16529  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
16530  *
16531  *     Context: May be called under interrupt context
16532  */
16533 
16534 static void
16535 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
16536 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
16537 {
16538 	struct buf	*cmd_bp;	/* buf for the original command */
16539 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
16540 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
16541 
16542 	ASSERT(un != NULL);
16543 	ASSERT(mutex_owned(SD_MUTEX(un)));
16544 	ASSERT(sense_bp != NULL);
16545 	ASSERT(sense_xp != NULL);
16546 	ASSERT(sense_pktp != NULL);
16547 
16548 	/*
16549 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
16550 	 * RQS command and not the original command.
16551 	 */
16552 	ASSERT(sense_pktp == un->un_rqs_pktp);
16553 	ASSERT(sense_bp   == un->un_rqs_bp);
16554 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
16555 	    (FLAG_SENSING | FLAG_HEAD));
16556 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
16557 	    FLAG_SENSING) == FLAG_SENSING);
16558 
16559 	/* These are the bp, xp, and pktp for the original command */
16560 	cmd_bp = sense_xp->xb_sense_bp;
16561 	cmd_xp = SD_GET_XBUF(cmd_bp);
16562 	cmd_pktp = SD_GET_PKTP(cmd_bp);
16563 
16564 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
16565 		/*
16566 		 * The REQUEST SENSE command failed.  Release the REQUEST
16567 		 * SENSE command for re-use, get back the bp for the original
16568 		 * command, and attempt to re-try the original command if
16569 		 * FLAG_DIAGNOSE is not set in the original packet.
16570 		 */
16571 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16572 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16573 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
16574 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
16575 			    NULL, NULL, EIO, (clock_t)0, NULL);
16576 			return;
16577 		}
16578 	}
16579 
16580 	/*
16581 	 * Save the relevant sense info into the xp for the original cmd.
16582 	 *
16583 	 * Note: if the request sense failed the state info will be zero
16584 	 * as set in sd_mark_rqs_busy()
16585 	 */
16586 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
16587 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
16588 	cmd_xp->xb_sense_resid  = sense_pktp->pkt_resid;
16589 	bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data, SENSE_LENGTH);
16590 
16591 	/*
16592 	 *  Free up the RQS command....
16593 	 *  NOTE:
16594 	 *	Must do this BEFORE calling sd_validate_sense_data!
16595 	 *	sd_validate_sense_data may return the original command in
16596 	 *	which case the pkt will be freed and the flags can no
16597 	 *	longer be touched.
16598 	 *	SD_MUTEX is held through this process until the command
16599 	 *	is dispatched based upon the sense data, so there are
16600 	 *	no race conditions.
16601 	 */
16602 	(void) sd_mark_rqs_idle(un, sense_xp);
16603 
16604 	/*
16605 	 * For a retryable command see if we have valid sense data, if so then
16606 	 * turn it over to sd_decode_sense() to figure out the right course of
16607 	 * action. Just fail a non-retryable command.
16608 	 */
16609 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16610 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp) ==
16611 		    SD_SENSE_DATA_IS_VALID) {
16612 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
16613 		}
16614 	} else {
16615 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
16616 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
16617 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
16618 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
16619 		sd_return_failed_command(un, cmd_bp, EIO);
16620 	}
16621 }
16622 
16623 
16624 
16625 
16626 /*
16627  *    Function: sd_handle_auto_request_sense
16628  *
16629  * Description: Processing for auto-request sense information.
16630  *
16631  *   Arguments: un - ptr to associated softstate
16632  *		bp - ptr to buf(9S) for the command
16633  *		xp - ptr to the sd_xbuf for the command
16634  *		pktp - ptr to the scsi_pkt(9S) for the command
16635  *
16636  *     Context: May be called under interrupt context
16637  */
16638 
16639 static void
16640 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
16641 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16642 {
16643 	struct scsi_arq_status *asp;
16644 
16645 	ASSERT(un != NULL);
16646 	ASSERT(mutex_owned(SD_MUTEX(un)));
16647 	ASSERT(bp != NULL);
16648 	ASSERT(xp != NULL);
16649 	ASSERT(pktp != NULL);
16650 	ASSERT(pktp != un->un_rqs_pktp);
16651 	ASSERT(bp   != un->un_rqs_bp);
16652 
16653 	/*
16654 	 * For auto-request sense, we get a scsi_arq_status back from
16655 	 * the HBA, with the sense data in the sts_sensedata member.
16656 	 * The pkt_scbp of the packet points to this scsi_arq_status.
16657 	 */
16658 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16659 
16660 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
16661 		/*
16662 		 * The auto REQUEST SENSE failed; see if we can re-try
16663 		 * the original command.
16664 		 */
16665 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16666 		    "auto request sense failed (reason=%s)\n",
16667 		    scsi_rname(asp->sts_rqpkt_reason));
16668 
16669 		sd_reset_target(un, pktp);
16670 
16671 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
16672 		    NULL, NULL, EIO, (clock_t)0, NULL);
16673 		return;
16674 	}
16675 
16676 	/* Save the relevant sense info into the xp for the original cmd. */
16677 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
16678 	xp->xb_sense_state  = asp->sts_rqpkt_state;
16679 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16680 	bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16681 	    min(sizeof (struct scsi_extended_sense), SENSE_LENGTH));
16682 
16683 	/*
16684 	 * See if we have valid sense data, if so then turn it over to
16685 	 * sd_decode_sense() to figure out the right course of action.
16686 	 */
16687 	if (sd_validate_sense_data(un, bp, xp) == SD_SENSE_DATA_IS_VALID) {
16688 		sd_decode_sense(un, bp, xp, pktp);
16689 	}
16690 }
16691 
16692 
16693 /*
16694  *    Function: sd_print_sense_failed_msg
16695  *
16696  * Description: Print log message when RQS has failed.
16697  *
16698  *   Arguments: un - ptr to associated softstate
16699  *		bp - ptr to buf(9S) for the command
16700  *		arg - generic message string ptr
16701  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16702  *			or SD_NO_RETRY_ISSUED
16703  *
16704  *     Context: May be called from interrupt context
16705  */
16706 
16707 static void
16708 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
16709 	int code)
16710 {
16711 	char	*msgp = arg;
16712 
16713 	ASSERT(un != NULL);
16714 	ASSERT(mutex_owned(SD_MUTEX(un)));
16715 	ASSERT(bp != NULL);
16716 
16717 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
16718 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
16719 	}
16720 }
16721 
16722 
16723 /*
16724  *    Function: sd_validate_sense_data
16725  *
16726  * Description: Check the given sense data for validity.
16727  *		If the sense data is not valid, the command will
16728  *		be either failed or retried!
16729  *
16730  * Return Code: SD_SENSE_DATA_IS_INVALID
16731  *		SD_SENSE_DATA_IS_VALID
16732  *
16733  *     Context: May be called from interrupt context
16734  */
16735 
16736 static int
16737 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp)
16738 {
16739 	struct scsi_extended_sense *esp;
16740 	struct	scsi_pkt *pktp;
16741 	size_t	actual_len;
16742 	char	*msgp = NULL;
16743 
16744 	ASSERT(un != NULL);
16745 	ASSERT(mutex_owned(SD_MUTEX(un)));
16746 	ASSERT(bp != NULL);
16747 	ASSERT(bp != un->un_rqs_bp);
16748 	ASSERT(xp != NULL);
16749 
16750 	pktp = SD_GET_PKTP(bp);
16751 	ASSERT(pktp != NULL);
16752 
16753 	/*
16754 	 * Check the status of the RQS command (auto or manual).
16755 	 */
16756 	switch (xp->xb_sense_status & STATUS_MASK) {
16757 	case STATUS_GOOD:
16758 		break;
16759 
16760 	case STATUS_RESERVATION_CONFLICT:
16761 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16762 		return (SD_SENSE_DATA_IS_INVALID);
16763 
16764 	case STATUS_BUSY:
16765 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16766 		    "Busy Status on REQUEST SENSE\n");
16767 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
16768 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
16769 		return (SD_SENSE_DATA_IS_INVALID);
16770 
16771 	case STATUS_QFULL:
16772 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16773 		    "QFULL Status on REQUEST SENSE\n");
16774 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
16775 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
16776 		return (SD_SENSE_DATA_IS_INVALID);
16777 
16778 	case STATUS_CHECK:
16779 	case STATUS_TERMINATED:
16780 		msgp = "Check Condition on REQUEST SENSE\n";
16781 		goto sense_failed;
16782 
16783 	default:
16784 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
16785 		goto sense_failed;
16786 	}
16787 
16788 	/*
16789 	 * See if we got the minimum required amount of sense data.
16790 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
16791 	 * or less.
16792 	 */
16793 	actual_len = (int)(SENSE_LENGTH - xp->xb_sense_resid);
16794 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
16795 	    (actual_len == 0)) {
16796 		msgp = "Request Sense couldn't get sense data\n";
16797 		goto sense_failed;
16798 	}
16799 
16800 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
16801 		msgp = "Not enough sense information\n";
16802 		goto sense_failed;
16803 	}
16804 
16805 	/*
16806 	 * We require the extended sense data
16807 	 */
16808 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
16809 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
16810 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16811 			static char tmp[8];
16812 			static char buf[148];
16813 			char *p = (char *)(xp->xb_sense_data);
16814 			int i;
16815 
16816 			mutex_enter(&sd_sense_mutex);
16817 			(void) strcpy(buf, "undecodable sense information:");
16818 			for (i = 0; i < actual_len; i++) {
16819 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
16820 				(void) strcpy(&buf[strlen(buf)], tmp);
16821 			}
16822 			i = strlen(buf);
16823 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
16824 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
16825 			mutex_exit(&sd_sense_mutex);
16826 		}
16827 		/* Note: Legacy behavior, fail the command with no retry */
16828 		sd_return_failed_command(un, bp, EIO);
16829 		return (SD_SENSE_DATA_IS_INVALID);
16830 	}
16831 
16832 	/*
16833 	 * Check that es_code is valid (es_class concatenated with es_code
16834 	 * make up the "response code" field.  es_class will always be 7, so
16835 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
16836 	 * format.
16837 	 */
16838 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
16839 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
16840 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
16841 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
16842 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
16843 		goto sense_failed;
16844 	}
16845 
16846 	return (SD_SENSE_DATA_IS_VALID);
16847 
16848 sense_failed:
16849 	/*
16850 	 * If the request sense failed (for whatever reason), attempt
16851 	 * to retry the original command.
16852 	 */
16853 #if defined(__i386) || defined(__amd64)
16854 	/*
16855 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
16856 	 * sddef.h for Sparc platform, and x86 uses 1 binary
16857 	 * for both SCSI/FC.
16858 	 * The SD_RETRY_DELAY value need to be adjusted here
16859 	 * when SD_RETRY_DELAY change in sddef.h
16860 	 */
16861 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
16862 	    sd_print_sense_failed_msg, msgp, EIO,
16863 		un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
16864 #else
16865 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
16866 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
16867 #endif
16868 
16869 	return (SD_SENSE_DATA_IS_INVALID);
16870 }
16871 
16872 
16873 
16874 /*
16875  *    Function: sd_decode_sense
16876  *
16877  * Description: Take recovery action(s) when SCSI Sense Data is received.
16878  *
16879  *     Context: Interrupt context.
16880  */
16881 
16882 static void
16883 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
16884 	struct scsi_pkt *pktp)
16885 {
16886 	struct scsi_extended_sense *esp;
16887 	struct scsi_descr_sense_hdr *sdsp;
16888 	uint8_t asc, ascq, sense_key;
16889 
16890 	ASSERT(un != NULL);
16891 	ASSERT(mutex_owned(SD_MUTEX(un)));
16892 	ASSERT(bp != NULL);
16893 	ASSERT(bp != un->un_rqs_bp);
16894 	ASSERT(xp != NULL);
16895 	ASSERT(pktp != NULL);
16896 
16897 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
16898 
16899 	switch (esp->es_code) {
16900 	case CODE_FMT_DESCR_CURRENT:
16901 	case CODE_FMT_DESCR_DEFERRED:
16902 		sdsp = (struct scsi_descr_sense_hdr *)xp->xb_sense_data;
16903 		sense_key = sdsp->ds_key;
16904 		asc = sdsp->ds_add_code;
16905 		ascq = sdsp->ds_qual_code;
16906 		break;
16907 	case CODE_FMT_VENDOR_SPECIFIC:
16908 	case CODE_FMT_FIXED_CURRENT:
16909 	case CODE_FMT_FIXED_DEFERRED:
16910 	default:
16911 		sense_key = esp->es_key;
16912 		asc = esp->es_add_code;
16913 		ascq = esp->es_qual_code;
16914 		break;
16915 	}
16916 
16917 	switch (sense_key) {
16918 	case KEY_NO_SENSE:
16919 		sd_sense_key_no_sense(un, bp, xp, pktp);
16920 		break;
16921 	case KEY_RECOVERABLE_ERROR:
16922 		sd_sense_key_recoverable_error(un, asc, bp, xp, pktp);
16923 		break;
16924 	case KEY_NOT_READY:
16925 		sd_sense_key_not_ready(un, asc, ascq, bp, xp, pktp);
16926 		break;
16927 	case KEY_MEDIUM_ERROR:
16928 	case KEY_HARDWARE_ERROR:
16929 		sd_sense_key_medium_or_hardware_error(un,
16930 		    sense_key, asc, bp, xp, pktp);
16931 		break;
16932 	case KEY_ILLEGAL_REQUEST:
16933 		sd_sense_key_illegal_request(un, bp, xp, pktp);
16934 		break;
16935 	case KEY_UNIT_ATTENTION:
16936 		sd_sense_key_unit_attention(un, asc, bp, xp, pktp);
16937 		break;
16938 	case KEY_WRITE_PROTECT:
16939 	case KEY_VOLUME_OVERFLOW:
16940 	case KEY_MISCOMPARE:
16941 		sd_sense_key_fail_command(un, bp, xp, pktp);
16942 		break;
16943 	case KEY_BLANK_CHECK:
16944 		sd_sense_key_blank_check(un, bp, xp, pktp);
16945 		break;
16946 	case KEY_ABORTED_COMMAND:
16947 		sd_sense_key_aborted_command(un, bp, xp, pktp);
16948 		break;
16949 	case KEY_VENDOR_UNIQUE:
16950 	case KEY_COPY_ABORTED:
16951 	case KEY_EQUAL:
16952 	case KEY_RESERVED:
16953 	default:
16954 		sd_sense_key_default(un, sense_key, bp, xp, pktp);
16955 		break;
16956 	}
16957 }
16958 
16959 
16960 /*
16961  *    Function: sd_dump_memory
16962  *
16963  * Description: Debug logging routine to print the contents of a user provided
16964  *		buffer. The output of the buffer is broken up into 256 byte
16965  *		segments due to a size constraint of the scsi_log.
16966  *		implementation.
16967  *
16968  *   Arguments: un - ptr to softstate
16969  *		comp - component mask
16970  *		title - "title" string to preceed data when printed
16971  *		data - ptr to data block to be printed
16972  *		len - size of data block to be printed
16973  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
16974  *
16975  *     Context: May be called from interrupt context
16976  */
16977 
16978 #define	SD_DUMP_MEMORY_BUF_SIZE	256
16979 
16980 static char *sd_dump_format_string[] = {
16981 		" 0x%02x",
16982 		" %c"
16983 };
16984 
16985 static void
16986 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
16987     int len, int fmt)
16988 {
16989 	int	i, j;
16990 	int	avail_count;
16991 	int	start_offset;
16992 	int	end_offset;
16993 	size_t	entry_len;
16994 	char	*bufp;
16995 	char	*local_buf;
16996 	char	*format_string;
16997 
16998 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
16999 
17000 	/*
17001 	 * In the debug version of the driver, this function is called from a
17002 	 * number of places which are NOPs in the release driver.
17003 	 * The debug driver therefore has additional methods of filtering
17004 	 * debug output.
17005 	 */
17006 #ifdef SDDEBUG
17007 	/*
17008 	 * In the debug version of the driver we can reduce the amount of debug
17009 	 * messages by setting sd_error_level to something other than
17010 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17011 	 * sd_component_mask.
17012 	 */
17013 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17014 	    (sd_error_level != SCSI_ERR_ALL)) {
17015 		return;
17016 	}
17017 	if (((sd_component_mask & comp) == 0) ||
17018 	    (sd_error_level != SCSI_ERR_ALL)) {
17019 		return;
17020 	}
17021 #else
17022 	if (sd_error_level != SCSI_ERR_ALL) {
17023 		return;
17024 	}
17025 #endif
17026 
17027 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17028 	bufp = local_buf;
17029 	/*
17030 	 * Available length is the length of local_buf[], minus the
17031 	 * length of the title string, minus one for the ":", minus
17032 	 * one for the newline, minus one for the NULL terminator.
17033 	 * This gives the #bytes available for holding the printed
17034 	 * values from the given data buffer.
17035 	 */
17036 	if (fmt == SD_LOG_HEX) {
17037 		format_string = sd_dump_format_string[0];
17038 	} else /* SD_LOG_CHAR */ {
17039 		format_string = sd_dump_format_string[1];
17040 	}
17041 	/*
17042 	 * Available count is the number of elements from the given
17043 	 * data buffer that we can fit into the available length.
17044 	 * This is based upon the size of the format string used.
17045 	 * Make one entry and find it's size.
17046 	 */
17047 	(void) sprintf(bufp, format_string, data[0]);
17048 	entry_len = strlen(bufp);
17049 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17050 
17051 	j = 0;
17052 	while (j < len) {
17053 		bufp = local_buf;
17054 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17055 		start_offset = j;
17056 
17057 		end_offset = start_offset + avail_count;
17058 
17059 		(void) sprintf(bufp, "%s:", title);
17060 		bufp += strlen(bufp);
17061 		for (i = start_offset; ((i < end_offset) && (j < len));
17062 		    i++, j++) {
17063 			(void) sprintf(bufp, format_string, data[i]);
17064 			bufp += entry_len;
17065 		}
17066 		(void) sprintf(bufp, "\n");
17067 
17068 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17069 	}
17070 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17071 }
17072 
17073 /*
17074  *    Function: sd_print_sense_msg
17075  *
17076  * Description: Log a message based upon the given sense data.
17077  *
17078  *   Arguments: un - ptr to associated softstate
17079  *		bp - ptr to buf(9S) for the command
17080  *		arg - ptr to associate sd_sense_info struct
17081  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17082  *			or SD_NO_RETRY_ISSUED
17083  *
17084  *     Context: May be called from interrupt context
17085  */
17086 
17087 static void
17088 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17089 {
17090 	struct sd_xbuf	*xp;
17091 	struct scsi_pkt	*pktp;
17092 	struct scsi_extended_sense *sensep;
17093 	daddr_t request_blkno;
17094 	diskaddr_t err_blkno;
17095 	int severity;
17096 	int pfa_flag;
17097 	int fixed_format = TRUE;
17098 	extern struct scsi_key_strings scsi_cmds[];
17099 
17100 	ASSERT(un != NULL);
17101 	ASSERT(mutex_owned(SD_MUTEX(un)));
17102 	ASSERT(bp != NULL);
17103 	xp = SD_GET_XBUF(bp);
17104 	ASSERT(xp != NULL);
17105 	pktp = SD_GET_PKTP(bp);
17106 	ASSERT(pktp != NULL);
17107 	ASSERT(arg != NULL);
17108 
17109 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17110 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17111 
17112 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17113 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17114 		severity = SCSI_ERR_RETRYABLE;
17115 	}
17116 
17117 	/* Use absolute block number for the request block number */
17118 	request_blkno = xp->xb_blkno;
17119 
17120 	/*
17121 	 * Now try to get the error block number from the sense data
17122 	 */
17123 	sensep = (struct scsi_extended_sense *)xp->xb_sense_data;
17124 	switch (sensep->es_code) {
17125 	case CODE_FMT_DESCR_CURRENT:
17126 	case CODE_FMT_DESCR_DEFERRED:
17127 		err_blkno =
17128 		    sd_extract_sense_info_descr(
17129 			(struct scsi_descr_sense_hdr *)sensep);
17130 		fixed_format = FALSE;
17131 		break;
17132 	case CODE_FMT_FIXED_CURRENT:
17133 	case CODE_FMT_FIXED_DEFERRED:
17134 	case CODE_FMT_VENDOR_SPECIFIC:
17135 	default:
17136 		/*
17137 		 * With the es_valid bit set, we assume that the error
17138 		 * blkno is in the sense data.  Also, if xp->xb_blkno is
17139 		 * greater than 0xffffffff then the target *should* have used
17140 		 * a descriptor sense format (or it shouldn't have set
17141 		 * the es_valid bit), and we may as well ignore the
17142 		 * 32-bit value.
17143 		 */
17144 		if ((sensep->es_valid != 0) && (xp->xb_blkno <= 0xffffffff)) {
17145 			err_blkno = (diskaddr_t)
17146 			    ((sensep->es_info_1 << 24) |
17147 			    (sensep->es_info_2 << 16) |
17148 			    (sensep->es_info_3 << 8)  |
17149 			    (sensep->es_info_4));
17150 		} else {
17151 			err_blkno = (diskaddr_t)-1;
17152 		}
17153 		break;
17154 	}
17155 
17156 	if (err_blkno == (diskaddr_t)-1) {
17157 		/*
17158 		 * Without the es_valid bit set (for fixed format) or an
17159 		 * information descriptor (for descriptor format) we cannot
17160 		 * be certain of the error blkno, so just use the
17161 		 * request_blkno.
17162 		 */
17163 		err_blkno = (diskaddr_t)request_blkno;
17164 	} else {
17165 		/*
17166 		 * We retrieved the error block number from the information
17167 		 * portion of the sense data.
17168 		 *
17169 		 * For USCSI commands we are better off using the error
17170 		 * block no. as the requested block no. (This is the best
17171 		 * we can estimate.)
17172 		 */
17173 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17174 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17175 			request_blkno = err_blkno;
17176 		}
17177 	}
17178 
17179 	/*
17180 	 * The following will log the buffer contents for the release driver
17181 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
17182 	 * level is set to verbose.
17183 	 */
17184 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
17185 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17186 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
17187 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
17188 
17189 	if (pfa_flag == FALSE) {
17190 		/* This is normally only set for USCSI */
17191 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
17192 			return;
17193 		}
17194 
17195 		if ((SD_IS_BUFIO(xp) == TRUE) &&
17196 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
17197 		    (severity < sd_error_level))) {
17198 			return;
17199 		}
17200 	}
17201 
17202 	/*
17203 	 * If the data is fixed format then check for Sonoma Failover,
17204 	 * and keep a count of how many failed I/O's.  We should not have
17205 	 * to worry about Sonoma returning descriptor format sense data,
17206 	 * and asc/ascq are in a different location in descriptor format.
17207 	 */
17208 	if (fixed_format &&
17209 	    (SD_IS_LSI(un)) && (sensep->es_key == KEY_ILLEGAL_REQUEST) &&
17210 	    (sensep->es_add_code == 0x94) && (sensep->es_qual_code == 0x01)) {
17211 		un->un_sonoma_failure_count++;
17212 		if (un->un_sonoma_failure_count > 1) {
17213 			return;
17214 		}
17215 	}
17216 
17217 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
17218 	    request_blkno, err_blkno, scsi_cmds, sensep,
17219 	    un->un_additional_codes, NULL);
17220 }
17221 
17222 /*
17223  *    Function: sd_extract_sense_info_descr
17224  *
17225  * Description: Retrieve "information" field from descriptor format
17226  *              sense data.  Iterates through each sense descriptor
17227  *              looking for the information descriptor and returns
17228  *              the information field from that descriptor.
17229  *
17230  *     Context: May be called from interrupt context
17231  */
17232 
17233 static diskaddr_t
17234 sd_extract_sense_info_descr(struct scsi_descr_sense_hdr *sdsp)
17235 {
17236 	diskaddr_t result;
17237 	uint8_t *descr_offset;
17238 	int valid_sense_length;
17239 	struct scsi_information_sense_descr *isd;
17240 
17241 	/*
17242 	 * Initialize result to -1 indicating there is no information
17243 	 * descriptor
17244 	 */
17245 	result = (diskaddr_t)-1;
17246 
17247 	/*
17248 	 * The first descriptor will immediately follow the header
17249 	 */
17250 	descr_offset = (uint8_t *)(sdsp+1); /* Pointer arithmetic */
17251 
17252 	/*
17253 	 * Calculate the amount of valid sense data
17254 	 */
17255 	valid_sense_length =
17256 	    min((sizeof (struct scsi_descr_sense_hdr) +
17257 	    sdsp->ds_addl_sense_length),
17258 	    SENSE_LENGTH);
17259 
17260 	/*
17261 	 * Iterate through the list of descriptors, stopping when we
17262 	 * run out of sense data
17263 	 */
17264 	while ((descr_offset + sizeof (struct scsi_information_sense_descr)) <=
17265 	    (uint8_t *)sdsp + valid_sense_length) {
17266 		/*
17267 		 * Check if this is an information descriptor.  We can
17268 		 * use the scsi_information_sense_descr structure as a
17269 		 * template sense the first two fields are always the
17270 		 * same
17271 		 */
17272 		isd = (struct scsi_information_sense_descr *)descr_offset;
17273 		if (isd->isd_descr_type == DESCR_INFORMATION) {
17274 			/*
17275 			 * Found an information descriptor.  Copy the
17276 			 * information field.  There will only be one
17277 			 * information descriptor so we can stop looking.
17278 			 */
17279 			result =
17280 			    (((diskaddr_t)isd->isd_information[0] << 56) |
17281 				((diskaddr_t)isd->isd_information[1] << 48) |
17282 				((diskaddr_t)isd->isd_information[2] << 40) |
17283 				((diskaddr_t)isd->isd_information[3] << 32) |
17284 				((diskaddr_t)isd->isd_information[4] << 24) |
17285 				((diskaddr_t)isd->isd_information[5] << 16) |
17286 				((diskaddr_t)isd->isd_information[6] << 8)  |
17287 				((diskaddr_t)isd->isd_information[7]));
17288 			break;
17289 		}
17290 
17291 		/*
17292 		 * Get pointer to the next descriptor.  The "additional
17293 		 * length" field holds the length of the descriptor except
17294 		 * for the "type" and "additional length" fields, so
17295 		 * we need to add 2 to get the total length.
17296 		 */
17297 		descr_offset += (isd->isd_addl_length + 2);
17298 	}
17299 
17300 	return (result);
17301 }
17302 
17303 /*
17304  *    Function: sd_sense_key_no_sense
17305  *
17306  * Description: Recovery action when sense data was not received.
17307  *
17308  *     Context: May be called from interrupt context
17309  */
17310 
17311 static void
17312 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
17313 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17314 {
17315 	struct sd_sense_info	si;
17316 
17317 	ASSERT(un != NULL);
17318 	ASSERT(mutex_owned(SD_MUTEX(un)));
17319 	ASSERT(bp != NULL);
17320 	ASSERT(xp != NULL);
17321 	ASSERT(pktp != NULL);
17322 
17323 	si.ssi_severity = SCSI_ERR_FATAL;
17324 	si.ssi_pfa_flag = FALSE;
17325 
17326 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17327 
17328 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17329 		&si, EIO, (clock_t)0, NULL);
17330 }
17331 
17332 
17333 /*
17334  *    Function: sd_sense_key_recoverable_error
17335  *
17336  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
17337  *
17338  *     Context: May be called from interrupt context
17339  */
17340 
17341 static void
17342 sd_sense_key_recoverable_error(struct sd_lun *un,
17343 	uint8_t asc,
17344 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17345 {
17346 	struct sd_sense_info	si;
17347 
17348 	ASSERT(un != NULL);
17349 	ASSERT(mutex_owned(SD_MUTEX(un)));
17350 	ASSERT(bp != NULL);
17351 	ASSERT(xp != NULL);
17352 	ASSERT(pktp != NULL);
17353 
17354 	/*
17355 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
17356 	 */
17357 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
17358 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17359 		si.ssi_severity = SCSI_ERR_INFO;
17360 		si.ssi_pfa_flag = TRUE;
17361 	} else {
17362 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
17363 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
17364 		si.ssi_severity = SCSI_ERR_RECOVERED;
17365 		si.ssi_pfa_flag = FALSE;
17366 	}
17367 
17368 	if (pktp->pkt_resid == 0) {
17369 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17370 		sd_return_command(un, bp);
17371 		return;
17372 	}
17373 
17374 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17375 	    &si, EIO, (clock_t)0, NULL);
17376 }
17377 
17378 
17379 
17380 
17381 /*
17382  *    Function: sd_sense_key_not_ready
17383  *
17384  * Description: Recovery actions for a SCSI "Not Ready" sense key.
17385  *
17386  *     Context: May be called from interrupt context
17387  */
17388 
17389 static void
17390 sd_sense_key_not_ready(struct sd_lun *un,
17391 	uint8_t asc, uint8_t ascq,
17392 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17393 {
17394 	struct sd_sense_info	si;
17395 
17396 	ASSERT(un != NULL);
17397 	ASSERT(mutex_owned(SD_MUTEX(un)));
17398 	ASSERT(bp != NULL);
17399 	ASSERT(xp != NULL);
17400 	ASSERT(pktp != NULL);
17401 
17402 	si.ssi_severity = SCSI_ERR_FATAL;
17403 	si.ssi_pfa_flag = FALSE;
17404 
17405 	/*
17406 	 * Update error stats after first NOT READY error. Disks may have
17407 	 * been powered down and may need to be restarted.  For CDROMs,
17408 	 * report NOT READY errors only if media is present.
17409 	 */
17410 	if ((ISCD(un) && (un->un_f_geometry_is_valid == TRUE)) ||
17411 	    (xp->xb_retry_count > 0)) {
17412 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17413 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
17414 	}
17415 
17416 	/*
17417 	 * Just fail if the "not ready" retry limit has been reached.
17418 	 */
17419 	if (xp->xb_retry_count >= un->un_notready_retry_count) {
17420 		/* Special check for error message printing for removables. */
17421 		if (un->un_f_has_removable_media && (asc == 0x04) &&
17422 		    (ascq >= 0x04)) {
17423 			si.ssi_severity = SCSI_ERR_ALL;
17424 		}
17425 		goto fail_command;
17426 	}
17427 
17428 	/*
17429 	 * Check the ASC and ASCQ in the sense data as needed, to determine
17430 	 * what to do.
17431 	 */
17432 	switch (asc) {
17433 	case 0x04:	/* LOGICAL UNIT NOT READY */
17434 		/*
17435 		 * disk drives that don't spin up result in a very long delay
17436 		 * in format without warning messages. We will log a message
17437 		 * if the error level is set to verbose.
17438 		 */
17439 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17440 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17441 			    "logical unit not ready, resetting disk\n");
17442 		}
17443 
17444 		/*
17445 		 * There are different requirements for CDROMs and disks for
17446 		 * the number of retries.  If a CD-ROM is giving this, it is
17447 		 * probably reading TOC and is in the process of getting
17448 		 * ready, so we should keep on trying for a long time to make
17449 		 * sure that all types of media are taken in account (for
17450 		 * some media the drive takes a long time to read TOC).  For
17451 		 * disks we do not want to retry this too many times as this
17452 		 * can cause a long hang in format when the drive refuses to
17453 		 * spin up (a very common failure).
17454 		 */
17455 		switch (ascq) {
17456 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
17457 			/*
17458 			 * Disk drives frequently refuse to spin up which
17459 			 * results in a very long hang in format without
17460 			 * warning messages.
17461 			 *
17462 			 * Note: This code preserves the legacy behavior of
17463 			 * comparing xb_retry_count against zero for fibre
17464 			 * channel targets instead of comparing against the
17465 			 * un_reset_retry_count value.  The reason for this
17466 			 * discrepancy has been so utterly lost beneath the
17467 			 * Sands of Time that even Indiana Jones could not
17468 			 * find it.
17469 			 */
17470 			if (un->un_f_is_fibre == TRUE) {
17471 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
17472 					(xp->xb_retry_count > 0)) &&
17473 					(un->un_startstop_timeid == NULL)) {
17474 					scsi_log(SD_DEVINFO(un), sd_label,
17475 					CE_WARN, "logical unit not ready, "
17476 					"resetting disk\n");
17477 					sd_reset_target(un, pktp);
17478 				}
17479 			} else {
17480 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
17481 					(xp->xb_retry_count >
17482 					un->un_reset_retry_count)) &&
17483 					(un->un_startstop_timeid == NULL)) {
17484 					scsi_log(SD_DEVINFO(un), sd_label,
17485 					CE_WARN, "logical unit not ready, "
17486 					"resetting disk\n");
17487 					sd_reset_target(un, pktp);
17488 				}
17489 			}
17490 			break;
17491 
17492 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
17493 			/*
17494 			 * If the target is in the process of becoming
17495 			 * ready, just proceed with the retry. This can
17496 			 * happen with CD-ROMs that take a long time to
17497 			 * read TOC after a power cycle or reset.
17498 			 */
17499 			goto do_retry;
17500 
17501 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
17502 			break;
17503 
17504 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
17505 			/*
17506 			 * Retries cannot help here so just fail right away.
17507 			 */
17508 			goto fail_command;
17509 
17510 		case 0x88:
17511 			/*
17512 			 * Vendor-unique code for T3/T4: it indicates a
17513 			 * path problem in a mutipathed config, but as far as
17514 			 * the target driver is concerned it equates to a fatal
17515 			 * error, so we should just fail the command right away
17516 			 * (without printing anything to the console). If this
17517 			 * is not a T3/T4, fall thru to the default recovery
17518 			 * action.
17519 			 * T3/T4 is FC only, don't need to check is_fibre
17520 			 */
17521 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
17522 				sd_return_failed_command(un, bp, EIO);
17523 				return;
17524 			}
17525 			/* FALLTHRU */
17526 
17527 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
17528 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
17529 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
17530 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
17531 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
17532 		default:    /* Possible future codes in SCSI spec? */
17533 			/*
17534 			 * For removable-media devices, do not retry if
17535 			 * ASCQ > 2 as these result mostly from USCSI commands
17536 			 * on MMC devices issued to check status of an
17537 			 * operation initiated in immediate mode.  Also for
17538 			 * ASCQ >= 4 do not print console messages as these
17539 			 * mainly represent a user-initiated operation
17540 			 * instead of a system failure.
17541 			 */
17542 			if (un->un_f_has_removable_media) {
17543 				si.ssi_severity = SCSI_ERR_ALL;
17544 				goto fail_command;
17545 			}
17546 			break;
17547 		}
17548 
17549 		/*
17550 		 * As part of our recovery attempt for the NOT READY
17551 		 * condition, we issue a START STOP UNIT command. However
17552 		 * we want to wait for a short delay before attempting this
17553 		 * as there may still be more commands coming back from the
17554 		 * target with the check condition. To do this we use
17555 		 * timeout(9F) to call sd_start_stop_unit_callback() after
17556 		 * the delay interval expires. (sd_start_stop_unit_callback()
17557 		 * dispatches sd_start_stop_unit_task(), which will issue
17558 		 * the actual START STOP UNIT command. The delay interval
17559 		 * is one-half of the delay that we will use to retry the
17560 		 * command that generated the NOT READY condition.
17561 		 *
17562 		 * Note that we could just dispatch sd_start_stop_unit_task()
17563 		 * from here and allow it to sleep for the delay interval,
17564 		 * but then we would be tying up the taskq thread
17565 		 * uncesessarily for the duration of the delay.
17566 		 *
17567 		 * Do not issue the START STOP UNIT if the current command
17568 		 * is already a START STOP UNIT.
17569 		 */
17570 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
17571 			break;
17572 		}
17573 
17574 		/*
17575 		 * Do not schedule the timeout if one is already pending.
17576 		 */
17577 		if (un->un_startstop_timeid != NULL) {
17578 			SD_INFO(SD_LOG_ERROR, un,
17579 			    "sd_sense_key_not_ready: restart already issued to"
17580 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
17581 			    ddi_get_instance(SD_DEVINFO(un)));
17582 			break;
17583 		}
17584 
17585 		/*
17586 		 * Schedule the START STOP UNIT command, then queue the command
17587 		 * for a retry.
17588 		 *
17589 		 * Note: A timeout is not scheduled for this retry because we
17590 		 * want the retry to be serial with the START_STOP_UNIT. The
17591 		 * retry will be started when the START_STOP_UNIT is completed
17592 		 * in sd_start_stop_unit_task.
17593 		 */
17594 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
17595 		    un, SD_BSY_TIMEOUT / 2);
17596 		xp->xb_retry_count++;
17597 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
17598 		return;
17599 
17600 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
17601 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17602 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17603 			    "unit does not respond to selection\n");
17604 		}
17605 		break;
17606 
17607 	case 0x3A:	/* MEDIUM NOT PRESENT */
17608 		if (sd_error_level >= SCSI_ERR_FATAL) {
17609 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17610 			    "Caddy not inserted in drive\n");
17611 		}
17612 
17613 		sr_ejected(un);
17614 		un->un_mediastate = DKIO_EJECTED;
17615 		/* The state has changed, inform the media watch routines */
17616 		cv_broadcast(&un->un_state_cv);
17617 		/* Just fail if no media is present in the drive. */
17618 		goto fail_command;
17619 
17620 	default:
17621 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17622 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
17623 			    "Unit not Ready. Additional sense code 0x%x\n",
17624 			    asc);
17625 		}
17626 		break;
17627 	}
17628 
17629 do_retry:
17630 
17631 	/*
17632 	 * Retry the command, as some targets may report NOT READY for
17633 	 * several seconds after being reset.
17634 	 */
17635 	xp->xb_retry_count++;
17636 	si.ssi_severity = SCSI_ERR_RETRYABLE;
17637 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17638 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
17639 
17640 	return;
17641 
17642 fail_command:
17643 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17644 	sd_return_failed_command(un, bp, EIO);
17645 }
17646 
17647 
17648 
17649 /*
17650  *    Function: sd_sense_key_medium_or_hardware_error
17651  *
17652  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
17653  *		sense key.
17654  *
17655  *     Context: May be called from interrupt context
17656  */
17657 
17658 static void
17659 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
17660 	int sense_key, uint8_t asc,
17661 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17662 {
17663 	struct sd_sense_info	si;
17664 
17665 	ASSERT(un != NULL);
17666 	ASSERT(mutex_owned(SD_MUTEX(un)));
17667 	ASSERT(bp != NULL);
17668 	ASSERT(xp != NULL);
17669 	ASSERT(pktp != NULL);
17670 
17671 	si.ssi_severity = SCSI_ERR_FATAL;
17672 	si.ssi_pfa_flag = FALSE;
17673 
17674 	if (sense_key == KEY_MEDIUM_ERROR) {
17675 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
17676 	}
17677 
17678 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17679 
17680 	if ((un->un_reset_retry_count != 0) &&
17681 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
17682 		mutex_exit(SD_MUTEX(un));
17683 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
17684 		if (un->un_f_allow_bus_device_reset == TRUE) {
17685 
17686 			boolean_t try_resetting_target = B_TRUE;
17687 
17688 			/*
17689 			 * We need to be able to handle specific ASC when we are
17690 			 * handling a KEY_HARDWARE_ERROR. In particular
17691 			 * taking the default action of resetting the target may
17692 			 * not be the appropriate way to attempt recovery.
17693 			 * Resetting a target because of a single LUN failure
17694 			 * victimizes all LUNs on that target.
17695 			 *
17696 			 * This is true for the LSI arrays, if an LSI
17697 			 * array controller returns an ASC of 0x84 (LUN Dead) we
17698 			 * should trust it.
17699 			 */
17700 
17701 			if (sense_key == KEY_HARDWARE_ERROR) {
17702 				switch (asc) {
17703 				case 0x84:
17704 					if (SD_IS_LSI(un)) {
17705 						try_resetting_target = B_FALSE;
17706 					}
17707 					break;
17708 				default:
17709 					break;
17710 				}
17711 			}
17712 
17713 			if (try_resetting_target == B_TRUE) {
17714 				int reset_retval = 0;
17715 				if (un->un_f_lun_reset_enabled == TRUE) {
17716 					SD_TRACE(SD_LOG_IO_CORE, un,
17717 					    "sd_sense_key_medium_or_hardware_"
17718 					    "error: issuing RESET_LUN\n");
17719 					reset_retval =
17720 					    scsi_reset(SD_ADDRESS(un),
17721 					    RESET_LUN);
17722 				}
17723 				if (reset_retval == 0) {
17724 					SD_TRACE(SD_LOG_IO_CORE, un,
17725 					    "sd_sense_key_medium_or_hardware_"
17726 					    "error: issuing RESET_TARGET\n");
17727 					(void) scsi_reset(SD_ADDRESS(un),
17728 					    RESET_TARGET);
17729 				}
17730 			}
17731 		}
17732 		mutex_enter(SD_MUTEX(un));
17733 	}
17734 
17735 	/*
17736 	 * This really ought to be a fatal error, but we will retry anyway
17737 	 * as some drives report this as a spurious error.
17738 	 */
17739 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17740 	    &si, EIO, (clock_t)0, NULL);
17741 }
17742 
17743 
17744 
17745 /*
17746  *    Function: sd_sense_key_illegal_request
17747  *
17748  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
17749  *
17750  *     Context: May be called from interrupt context
17751  */
17752 
17753 static void
17754 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
17755 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17756 {
17757 	struct sd_sense_info	si;
17758 
17759 	ASSERT(un != NULL);
17760 	ASSERT(mutex_owned(SD_MUTEX(un)));
17761 	ASSERT(bp != NULL);
17762 	ASSERT(xp != NULL);
17763 	ASSERT(pktp != NULL);
17764 
17765 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17766 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
17767 
17768 	si.ssi_severity = SCSI_ERR_INFO;
17769 	si.ssi_pfa_flag = FALSE;
17770 
17771 	/* Pointless to retry if the target thinks it's an illegal request */
17772 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17773 	sd_return_failed_command(un, bp, EIO);
17774 }
17775 
17776 
17777 
17778 
17779 /*
17780  *    Function: sd_sense_key_unit_attention
17781  *
17782  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
17783  *
17784  *     Context: May be called from interrupt context
17785  */
17786 
17787 static void
17788 sd_sense_key_unit_attention(struct sd_lun *un,
17789 	uint8_t asc,
17790 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17791 {
17792 	/*
17793 	 * For UNIT ATTENTION we allow retries for one minute. Devices
17794 	 * like Sonoma can return UNIT ATTENTION close to a minute
17795 	 * under certain conditions.
17796 	 */
17797 	int	retry_check_flag = SD_RETRIES_UA;
17798 	boolean_t	kstat_updated = B_FALSE;
17799 	struct	sd_sense_info		si;
17800 
17801 	ASSERT(un != NULL);
17802 	ASSERT(mutex_owned(SD_MUTEX(un)));
17803 	ASSERT(bp != NULL);
17804 	ASSERT(xp != NULL);
17805 	ASSERT(pktp != NULL);
17806 
17807 	si.ssi_severity = SCSI_ERR_INFO;
17808 	si.ssi_pfa_flag = FALSE;
17809 
17810 
17811 	switch (asc) {
17812 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
17813 		if (sd_report_pfa != 0) {
17814 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17815 			si.ssi_pfa_flag = TRUE;
17816 			retry_check_flag = SD_RETRIES_STANDARD;
17817 			goto do_retry;
17818 		}
17819 		break;
17820 
17821 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
17822 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
17823 			un->un_resvd_status |=
17824 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
17825 		}
17826 		/* FALLTHRU */
17827 
17828 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
17829 		if (!un->un_f_has_removable_media) {
17830 			break;
17831 		}
17832 
17833 		/*
17834 		 * When we get a unit attention from a removable-media device,
17835 		 * it may be in a state that will take a long time to recover
17836 		 * (e.g., from a reset).  Since we are executing in interrupt
17837 		 * context here, we cannot wait around for the device to come
17838 		 * back. So hand this command off to sd_media_change_task()
17839 		 * for deferred processing under taskq thread context. (Note
17840 		 * that the command still may be failed if a problem is
17841 		 * encountered at a later time.)
17842 		 */
17843 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
17844 		    KM_NOSLEEP) == 0) {
17845 			/*
17846 			 * Cannot dispatch the request so fail the command.
17847 			 */
17848 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
17849 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17850 			si.ssi_severity = SCSI_ERR_FATAL;
17851 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17852 			sd_return_failed_command(un, bp, EIO);
17853 		}
17854 
17855 		/*
17856 		 * If failed to dispatch sd_media_change_task(), we already
17857 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
17858 		 * we should update kstat later if it encounters an error. So,
17859 		 * we update kstat_updated flag here.
17860 		 */
17861 		kstat_updated = B_TRUE;
17862 
17863 		/*
17864 		 * Either the command has been successfully dispatched to a
17865 		 * task Q for retrying, or the dispatch failed. In either case
17866 		 * do NOT retry again by calling sd_retry_command. This sets up
17867 		 * two retries of the same command and when one completes and
17868 		 * frees the resources the other will access freed memory,
17869 		 * a bad thing.
17870 		 */
17871 		return;
17872 
17873 	default:
17874 		break;
17875 	}
17876 
17877 	/*
17878 	 * Update kstat if we haven't done that.
17879 	 */
17880 	if (!kstat_updated) {
17881 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17882 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17883 	}
17884 
17885 do_retry:
17886 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
17887 	    EIO, SD_UA_RETRY_DELAY, NULL);
17888 }
17889 
17890 
17891 
17892 /*
17893  *    Function: sd_sense_key_fail_command
17894  *
17895  * Description: Use to fail a command when we don't like the sense key that
17896  *		was returned.
17897  *
17898  *     Context: May be called from interrupt context
17899  */
17900 
17901 static void
17902 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
17903 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17904 {
17905 	struct sd_sense_info	si;
17906 
17907 	ASSERT(un != NULL);
17908 	ASSERT(mutex_owned(SD_MUTEX(un)));
17909 	ASSERT(bp != NULL);
17910 	ASSERT(xp != NULL);
17911 	ASSERT(pktp != NULL);
17912 
17913 	si.ssi_severity = SCSI_ERR_FATAL;
17914 	si.ssi_pfa_flag = FALSE;
17915 
17916 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17917 	sd_return_failed_command(un, bp, EIO);
17918 }
17919 
17920 
17921 
17922 /*
17923  *    Function: sd_sense_key_blank_check
17924  *
17925  * Description: Recovery actions for a SCSI "Blank Check" sense key.
17926  *		Has no monetary connotation.
17927  *
17928  *     Context: May be called from interrupt context
17929  */
17930 
17931 static void
17932 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
17933 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17934 {
17935 	struct sd_sense_info	si;
17936 
17937 	ASSERT(un != NULL);
17938 	ASSERT(mutex_owned(SD_MUTEX(un)));
17939 	ASSERT(bp != NULL);
17940 	ASSERT(xp != NULL);
17941 	ASSERT(pktp != NULL);
17942 
17943 	/*
17944 	 * Blank check is not fatal for removable devices, therefore
17945 	 * it does not require a console message.
17946 	 */
17947 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
17948 	    SCSI_ERR_FATAL;
17949 	si.ssi_pfa_flag = FALSE;
17950 
17951 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17952 	sd_return_failed_command(un, bp, EIO);
17953 }
17954 
17955 
17956 
17957 
17958 /*
17959  *    Function: sd_sense_key_aborted_command
17960  *
17961  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
17962  *
17963  *     Context: May be called from interrupt context
17964  */
17965 
17966 static void
17967 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
17968 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17969 {
17970 	struct sd_sense_info	si;
17971 
17972 	ASSERT(un != NULL);
17973 	ASSERT(mutex_owned(SD_MUTEX(un)));
17974 	ASSERT(bp != NULL);
17975 	ASSERT(xp != NULL);
17976 	ASSERT(pktp != NULL);
17977 
17978 	si.ssi_severity = SCSI_ERR_FATAL;
17979 	si.ssi_pfa_flag = FALSE;
17980 
17981 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17982 
17983 	/*
17984 	 * This really ought to be a fatal error, but we will retry anyway
17985 	 * as some drives report this as a spurious error.
17986 	 */
17987 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17988 	    &si, EIO, (clock_t)0, NULL);
17989 }
17990 
17991 
17992 
17993 /*
17994  *    Function: sd_sense_key_default
17995  *
17996  * Description: Default recovery action for several SCSI sense keys (basically
17997  *		attempts a retry).
17998  *
17999  *     Context: May be called from interrupt context
18000  */
18001 
18002 static void
18003 sd_sense_key_default(struct sd_lun *un,
18004 	int sense_key,
18005 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18006 {
18007 	struct sd_sense_info	si;
18008 
18009 	ASSERT(un != NULL);
18010 	ASSERT(mutex_owned(SD_MUTEX(un)));
18011 	ASSERT(bp != NULL);
18012 	ASSERT(xp != NULL);
18013 	ASSERT(pktp != NULL);
18014 
18015 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18016 
18017 	/*
18018 	 * Undecoded sense key.	Attempt retries and hope that will fix
18019 	 * the problem.  Otherwise, we're dead.
18020 	 */
18021 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18022 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18023 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18024 	}
18025 
18026 	si.ssi_severity = SCSI_ERR_FATAL;
18027 	si.ssi_pfa_flag = FALSE;
18028 
18029 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18030 	    &si, EIO, (clock_t)0, NULL);
18031 }
18032 
18033 
18034 
18035 /*
18036  *    Function: sd_print_retry_msg
18037  *
18038  * Description: Print a message indicating the retry action being taken.
18039  *
18040  *   Arguments: un - ptr to associated softstate
18041  *		bp - ptr to buf(9S) for the command
18042  *		arg - not used.
18043  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18044  *			or SD_NO_RETRY_ISSUED
18045  *
18046  *     Context: May be called from interrupt context
18047  */
18048 /* ARGSUSED */
18049 static void
18050 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18051 {
18052 	struct sd_xbuf	*xp;
18053 	struct scsi_pkt *pktp;
18054 	char *reasonp;
18055 	char *msgp;
18056 
18057 	ASSERT(un != NULL);
18058 	ASSERT(mutex_owned(SD_MUTEX(un)));
18059 	ASSERT(bp != NULL);
18060 	pktp = SD_GET_PKTP(bp);
18061 	ASSERT(pktp != NULL);
18062 	xp = SD_GET_XBUF(bp);
18063 	ASSERT(xp != NULL);
18064 
18065 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18066 	mutex_enter(&un->un_pm_mutex);
18067 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18068 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18069 	    (pktp->pkt_flags & FLAG_SILENT)) {
18070 		mutex_exit(&un->un_pm_mutex);
18071 		goto update_pkt_reason;
18072 	}
18073 	mutex_exit(&un->un_pm_mutex);
18074 
18075 	/*
18076 	 * Suppress messages if they are all the same pkt_reason; with
18077 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18078 	 * If we are in panic, then suppress the retry messages.
18079 	 */
18080 	switch (flag) {
18081 	case SD_NO_RETRY_ISSUED:
18082 		msgp = "giving up";
18083 		break;
18084 	case SD_IMMEDIATE_RETRY_ISSUED:
18085 	case SD_DELAYED_RETRY_ISSUED:
18086 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18087 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18088 		    (sd_error_level != SCSI_ERR_ALL))) {
18089 			return;
18090 		}
18091 		msgp = "retrying command";
18092 		break;
18093 	default:
18094 		goto update_pkt_reason;
18095 	}
18096 
18097 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18098 	    scsi_rname(pktp->pkt_reason));
18099 
18100 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18101 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18102 
18103 update_pkt_reason:
18104 	/*
18105 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18106 	 * This is to prevent multiple console messages for the same failure
18107 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18108 	 * when the command is retried successfully because there still may be
18109 	 * more commands coming back with the same value of pktp->pkt_reason.
18110 	 */
18111 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18112 		un->un_last_pkt_reason = pktp->pkt_reason;
18113 	}
18114 }
18115 
18116 
18117 /*
18118  *    Function: sd_print_cmd_incomplete_msg
18119  *
18120  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18121  *
18122  *   Arguments: un - ptr to associated softstate
18123  *		bp - ptr to buf(9S) for the command
18124  *		arg - passed to sd_print_retry_msg()
18125  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18126  *			or SD_NO_RETRY_ISSUED
18127  *
18128  *     Context: May be called from interrupt context
18129  */
18130 
18131 static void
18132 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18133 	int code)
18134 {
18135 	dev_info_t	*dip;
18136 
18137 	ASSERT(un != NULL);
18138 	ASSERT(mutex_owned(SD_MUTEX(un)));
18139 	ASSERT(bp != NULL);
18140 
18141 	switch (code) {
18142 	case SD_NO_RETRY_ISSUED:
18143 		/* Command was failed. Someone turned off this target? */
18144 		if (un->un_state != SD_STATE_OFFLINE) {
18145 			/*
18146 			 * Suppress message if we are detaching and
18147 			 * device has been disconnected
18148 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18149 			 * private interface and not part of the DDI
18150 			 */
18151 			dip = un->un_sd->sd_dev;
18152 			if (!(DEVI_IS_DETACHING(dip) &&
18153 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18154 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18155 				"disk not responding to selection\n");
18156 			}
18157 			New_state(un, SD_STATE_OFFLINE);
18158 		}
18159 		break;
18160 
18161 	case SD_DELAYED_RETRY_ISSUED:
18162 	case SD_IMMEDIATE_RETRY_ISSUED:
18163 	default:
18164 		/* Command was successfully queued for retry */
18165 		sd_print_retry_msg(un, bp, arg, code);
18166 		break;
18167 	}
18168 }
18169 
18170 
18171 /*
18172  *    Function: sd_pkt_reason_cmd_incomplete
18173  *
18174  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18175  *
18176  *     Context: May be called from interrupt context
18177  */
18178 
18179 static void
18180 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18181 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18182 {
18183 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18184 
18185 	ASSERT(un != NULL);
18186 	ASSERT(mutex_owned(SD_MUTEX(un)));
18187 	ASSERT(bp != NULL);
18188 	ASSERT(xp != NULL);
18189 	ASSERT(pktp != NULL);
18190 
18191 	/* Do not do a reset if selection did not complete */
18192 	/* Note: Should this not just check the bit? */
18193 	if (pktp->pkt_state != STATE_GOT_BUS) {
18194 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18195 		sd_reset_target(un, pktp);
18196 	}
18197 
18198 	/*
18199 	 * If the target was not successfully selected, then set
18200 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18201 	 * with the target, and further retries and/or commands are
18202 	 * likely to take a long time.
18203 	 */
18204 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18205 		flag |= SD_RETRIES_FAILFAST;
18206 	}
18207 
18208 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18209 
18210 	sd_retry_command(un, bp, flag,
18211 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18212 }
18213 
18214 
18215 
18216 /*
18217  *    Function: sd_pkt_reason_cmd_tran_err
18218  *
18219  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
18220  *
18221  *     Context: May be called from interrupt context
18222  */
18223 
18224 static void
18225 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
18226 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18227 {
18228 	ASSERT(un != NULL);
18229 	ASSERT(mutex_owned(SD_MUTEX(un)));
18230 	ASSERT(bp != NULL);
18231 	ASSERT(xp != NULL);
18232 	ASSERT(pktp != NULL);
18233 
18234 	/*
18235 	 * Do not reset if we got a parity error, or if
18236 	 * selection did not complete.
18237 	 */
18238 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18239 	/* Note: Should this not just check the bit for pkt_state? */
18240 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
18241 	    (pktp->pkt_state != STATE_GOT_BUS)) {
18242 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18243 		sd_reset_target(un, pktp);
18244 	}
18245 
18246 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18247 
18248 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18249 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18250 }
18251 
18252 
18253 
18254 /*
18255  *    Function: sd_pkt_reason_cmd_reset
18256  *
18257  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
18258  *
18259  *     Context: May be called from interrupt context
18260  */
18261 
18262 static void
18263 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
18264 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18265 {
18266 	ASSERT(un != NULL);
18267 	ASSERT(mutex_owned(SD_MUTEX(un)));
18268 	ASSERT(bp != NULL);
18269 	ASSERT(xp != NULL);
18270 	ASSERT(pktp != NULL);
18271 
18272 	/* The target may still be running the command, so try to reset. */
18273 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18274 	sd_reset_target(un, pktp);
18275 
18276 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18277 
18278 	/*
18279 	 * If pkt_reason is CMD_RESET chances are that this pkt got
18280 	 * reset because another target on this bus caused it. The target
18281 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18282 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18283 	 */
18284 
18285 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18286 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18287 }
18288 
18289 
18290 
18291 
18292 /*
18293  *    Function: sd_pkt_reason_cmd_aborted
18294  *
18295  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
18296  *
18297  *     Context: May be called from interrupt context
18298  */
18299 
18300 static void
18301 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
18302 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18303 {
18304 	ASSERT(un != NULL);
18305 	ASSERT(mutex_owned(SD_MUTEX(un)));
18306 	ASSERT(bp != NULL);
18307 	ASSERT(xp != NULL);
18308 	ASSERT(pktp != NULL);
18309 
18310 	/* The target may still be running the command, so try to reset. */
18311 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18312 	sd_reset_target(un, pktp);
18313 
18314 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18315 
18316 	/*
18317 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
18318 	 * aborted because another target on this bus caused it. The target
18319 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18320 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18321 	 */
18322 
18323 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18324 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18325 }
18326 
18327 
18328 
18329 /*
18330  *    Function: sd_pkt_reason_cmd_timeout
18331  *
18332  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
18333  *
18334  *     Context: May be called from interrupt context
18335  */
18336 
18337 static void
18338 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
18339 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18340 {
18341 	ASSERT(un != NULL);
18342 	ASSERT(mutex_owned(SD_MUTEX(un)));
18343 	ASSERT(bp != NULL);
18344 	ASSERT(xp != NULL);
18345 	ASSERT(pktp != NULL);
18346 
18347 
18348 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18349 	sd_reset_target(un, pktp);
18350 
18351 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18352 
18353 	/*
18354 	 * A command timeout indicates that we could not establish
18355 	 * communication with the target, so set SD_RETRIES_FAILFAST
18356 	 * as further retries/commands are likely to take a long time.
18357 	 */
18358 	sd_retry_command(un, bp,
18359 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
18360 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18361 }
18362 
18363 
18364 
18365 /*
18366  *    Function: sd_pkt_reason_cmd_unx_bus_free
18367  *
18368  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
18369  *
18370  *     Context: May be called from interrupt context
18371  */
18372 
18373 static void
18374 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
18375 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18376 {
18377 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
18378 
18379 	ASSERT(un != NULL);
18380 	ASSERT(mutex_owned(SD_MUTEX(un)));
18381 	ASSERT(bp != NULL);
18382 	ASSERT(xp != NULL);
18383 	ASSERT(pktp != NULL);
18384 
18385 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18386 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18387 
18388 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
18389 	    sd_print_retry_msg : NULL;
18390 
18391 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18392 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18393 }
18394 
18395 
18396 /*
18397  *    Function: sd_pkt_reason_cmd_tag_reject
18398  *
18399  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
18400  *
18401  *     Context: May be called from interrupt context
18402  */
18403 
18404 static void
18405 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
18406 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18407 {
18408 	ASSERT(un != NULL);
18409 	ASSERT(mutex_owned(SD_MUTEX(un)));
18410 	ASSERT(bp != NULL);
18411 	ASSERT(xp != NULL);
18412 	ASSERT(pktp != NULL);
18413 
18414 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18415 	pktp->pkt_flags = 0;
18416 	un->un_tagflags = 0;
18417 	if (un->un_f_opt_queueing == TRUE) {
18418 		un->un_throttle = min(un->un_throttle, 3);
18419 	} else {
18420 		un->un_throttle = 1;
18421 	}
18422 	mutex_exit(SD_MUTEX(un));
18423 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
18424 	mutex_enter(SD_MUTEX(un));
18425 
18426 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18427 
18428 	/* Legacy behavior not to check retry counts here. */
18429 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
18430 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18431 }
18432 
18433 
18434 /*
18435  *    Function: sd_pkt_reason_default
18436  *
18437  * Description: Default recovery actions for SCSA pkt_reason values that
18438  *		do not have more explicit recovery actions.
18439  *
18440  *     Context: May be called from interrupt context
18441  */
18442 
18443 static void
18444 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
18445 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18446 {
18447 	ASSERT(un != NULL);
18448 	ASSERT(mutex_owned(SD_MUTEX(un)));
18449 	ASSERT(bp != NULL);
18450 	ASSERT(xp != NULL);
18451 	ASSERT(pktp != NULL);
18452 
18453 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18454 	sd_reset_target(un, pktp);
18455 
18456 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18457 
18458 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18459 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18460 }
18461 
18462 
18463 
18464 /*
18465  *    Function: sd_pkt_status_check_condition
18466  *
18467  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
18468  *
18469  *     Context: May be called from interrupt context
18470  */
18471 
18472 static void
18473 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
18474 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18475 {
18476 	ASSERT(un != NULL);
18477 	ASSERT(mutex_owned(SD_MUTEX(un)));
18478 	ASSERT(bp != NULL);
18479 	ASSERT(xp != NULL);
18480 	ASSERT(pktp != NULL);
18481 
18482 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
18483 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
18484 
18485 	/*
18486 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
18487 	 * command will be retried after the request sense). Otherwise, retry
18488 	 * the command. Note: we are issuing the request sense even though the
18489 	 * retry limit may have been reached for the failed command.
18490 	 */
18491 	if (un->un_f_arq_enabled == FALSE) {
18492 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
18493 		    "no ARQ, sending request sense command\n");
18494 		sd_send_request_sense_command(un, bp, pktp);
18495 	} else {
18496 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
18497 		    "ARQ,retrying request sense command\n");
18498 #if defined(__i386) || defined(__amd64)
18499 		/*
18500 		 * The SD_RETRY_DELAY value need to be adjusted here
18501 		 * when SD_RETRY_DELAY change in sddef.h
18502 		 */
18503 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
18504 			un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
18505 			NULL);
18506 #else
18507 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
18508 		    EIO, SD_RETRY_DELAY, NULL);
18509 #endif
18510 	}
18511 
18512 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
18513 }
18514 
18515 
18516 /*
18517  *    Function: sd_pkt_status_busy
18518  *
18519  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
18520  *
18521  *     Context: May be called from interrupt context
18522  */
18523 
18524 static void
18525 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18526 	struct scsi_pkt *pktp)
18527 {
18528 	ASSERT(un != NULL);
18529 	ASSERT(mutex_owned(SD_MUTEX(un)));
18530 	ASSERT(bp != NULL);
18531 	ASSERT(xp != NULL);
18532 	ASSERT(pktp != NULL);
18533 
18534 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18535 	    "sd_pkt_status_busy: entry\n");
18536 
18537 	/* If retries are exhausted, just fail the command. */
18538 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
18539 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18540 		    "device busy too long\n");
18541 		sd_return_failed_command(un, bp, EIO);
18542 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18543 		    "sd_pkt_status_busy: exit\n");
18544 		return;
18545 	}
18546 	xp->xb_retry_count++;
18547 
18548 	/*
18549 	 * Try to reset the target. However, we do not want to perform
18550 	 * more than one reset if the device continues to fail. The reset
18551 	 * will be performed when the retry count reaches the reset
18552 	 * threshold.  This threshold should be set such that at least
18553 	 * one retry is issued before the reset is performed.
18554 	 */
18555 	if (xp->xb_retry_count ==
18556 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
18557 		int rval = 0;
18558 		mutex_exit(SD_MUTEX(un));
18559 		if (un->un_f_allow_bus_device_reset == TRUE) {
18560 			/*
18561 			 * First try to reset the LUN; if we cannot then
18562 			 * try to reset the target.
18563 			 */
18564 			if (un->un_f_lun_reset_enabled == TRUE) {
18565 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18566 				    "sd_pkt_status_busy: RESET_LUN\n");
18567 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
18568 			}
18569 			if (rval == 0) {
18570 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18571 				    "sd_pkt_status_busy: RESET_TARGET\n");
18572 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
18573 			}
18574 		}
18575 		if (rval == 0) {
18576 			/*
18577 			 * If the RESET_LUN and/or RESET_TARGET failed,
18578 			 * try RESET_ALL
18579 			 */
18580 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18581 			    "sd_pkt_status_busy: RESET_ALL\n");
18582 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
18583 		}
18584 		mutex_enter(SD_MUTEX(un));
18585 		if (rval == 0) {
18586 			/*
18587 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
18588 			 * At this point we give up & fail the command.
18589 			 */
18590 			sd_return_failed_command(un, bp, EIO);
18591 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18592 			    "sd_pkt_status_busy: exit (failed cmd)\n");
18593 			return;
18594 		}
18595 	}
18596 
18597 	/*
18598 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
18599 	 * we have already checked the retry counts above.
18600 	 */
18601 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
18602 	    EIO, SD_BSY_TIMEOUT, NULL);
18603 
18604 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18605 	    "sd_pkt_status_busy: exit\n");
18606 }
18607 
18608 
18609 /*
18610  *    Function: sd_pkt_status_reservation_conflict
18611  *
18612  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
18613  *		command status.
18614  *
18615  *     Context: May be called from interrupt context
18616  */
18617 
18618 static void
18619 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
18620 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18621 {
18622 	ASSERT(un != NULL);
18623 	ASSERT(mutex_owned(SD_MUTEX(un)));
18624 	ASSERT(bp != NULL);
18625 	ASSERT(xp != NULL);
18626 	ASSERT(pktp != NULL);
18627 
18628 	/*
18629 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
18630 	 * conflict could be due to various reasons like incorrect keys, not
18631 	 * registered or not reserved etc. So, we return EACCES to the caller.
18632 	 */
18633 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
18634 		int cmd = SD_GET_PKT_OPCODE(pktp);
18635 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
18636 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
18637 			sd_return_failed_command(un, bp, EACCES);
18638 			return;
18639 		}
18640 	}
18641 
18642 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
18643 
18644 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
18645 		if (sd_failfast_enable != 0) {
18646 			/* By definition, we must panic here.... */
18647 			sd_panic_for_res_conflict(un);
18648 			/*NOTREACHED*/
18649 		}
18650 		SD_ERROR(SD_LOG_IO, un,
18651 		    "sd_handle_resv_conflict: Disk Reserved\n");
18652 		sd_return_failed_command(un, bp, EACCES);
18653 		return;
18654 	}
18655 
18656 	/*
18657 	 * 1147670: retry only if sd_retry_on_reservation_conflict
18658 	 * property is set (default is 1). Retries will not succeed
18659 	 * on a disk reserved by another initiator. HA systems
18660 	 * may reset this via sd.conf to avoid these retries.
18661 	 *
18662 	 * Note: The legacy return code for this failure is EIO, however EACCES
18663 	 * seems more appropriate for a reservation conflict.
18664 	 */
18665 	if (sd_retry_on_reservation_conflict == 0) {
18666 		SD_ERROR(SD_LOG_IO, un,
18667 		    "sd_handle_resv_conflict: Device Reserved\n");
18668 		sd_return_failed_command(un, bp, EIO);
18669 		return;
18670 	}
18671 
18672 	/*
18673 	 * Retry the command if we can.
18674 	 *
18675 	 * Note: The legacy return code for this failure is EIO, however EACCES
18676 	 * seems more appropriate for a reservation conflict.
18677 	 */
18678 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
18679 	    (clock_t)2, NULL);
18680 }
18681 
18682 
18683 
18684 /*
18685  *    Function: sd_pkt_status_qfull
18686  *
18687  * Description: Handle a QUEUE FULL condition from the target.  This can
18688  *		occur if the HBA does not handle the queue full condition.
18689  *		(Basically this means third-party HBAs as Sun HBAs will
18690  *		handle the queue full condition.)  Note that if there are
18691  *		some commands already in the transport, then the queue full
18692  *		has occurred because the queue for this nexus is actually
18693  *		full. If there are no commands in the transport, then the
18694  *		queue full is resulting from some other initiator or lun
18695  *		consuming all the resources at the target.
18696  *
18697  *     Context: May be called from interrupt context
18698  */
18699 
18700 static void
18701 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
18702 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18703 {
18704 	ASSERT(un != NULL);
18705 	ASSERT(mutex_owned(SD_MUTEX(un)));
18706 	ASSERT(bp != NULL);
18707 	ASSERT(xp != NULL);
18708 	ASSERT(pktp != NULL);
18709 
18710 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18711 	    "sd_pkt_status_qfull: entry\n");
18712 
18713 	/*
18714 	 * Just lower the QFULL throttle and retry the command.  Note that
18715 	 * we do not limit the number of retries here.
18716 	 */
18717 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
18718 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
18719 	    SD_RESTART_TIMEOUT, NULL);
18720 
18721 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18722 	    "sd_pkt_status_qfull: exit\n");
18723 }
18724 
18725 
18726 /*
18727  *    Function: sd_reset_target
18728  *
18729  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
18730  *		RESET_TARGET, or RESET_ALL.
18731  *
18732  *     Context: May be called under interrupt context.
18733  */
18734 
18735 static void
18736 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
18737 {
18738 	int rval = 0;
18739 
18740 	ASSERT(un != NULL);
18741 	ASSERT(mutex_owned(SD_MUTEX(un)));
18742 	ASSERT(pktp != NULL);
18743 
18744 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
18745 
18746 	/*
18747 	 * No need to reset if the transport layer has already done so.
18748 	 */
18749 	if ((pktp->pkt_statistics &
18750 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
18751 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18752 		    "sd_reset_target: no reset\n");
18753 		return;
18754 	}
18755 
18756 	mutex_exit(SD_MUTEX(un));
18757 
18758 	if (un->un_f_allow_bus_device_reset == TRUE) {
18759 		if (un->un_f_lun_reset_enabled == TRUE) {
18760 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18761 			    "sd_reset_target: RESET_LUN\n");
18762 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
18763 		}
18764 		if (rval == 0) {
18765 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18766 			    "sd_reset_target: RESET_TARGET\n");
18767 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
18768 		}
18769 	}
18770 
18771 	if (rval == 0) {
18772 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18773 		    "sd_reset_target: RESET_ALL\n");
18774 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
18775 	}
18776 
18777 	mutex_enter(SD_MUTEX(un));
18778 
18779 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
18780 }
18781 
18782 
18783 /*
18784  *    Function: sd_media_change_task
18785  *
18786  * Description: Recovery action for CDROM to become available.
18787  *
18788  *     Context: Executes in a taskq() thread context
18789  */
18790 
18791 static void
18792 sd_media_change_task(void *arg)
18793 {
18794 	struct	scsi_pkt	*pktp = arg;
18795 	struct	sd_lun		*un;
18796 	struct	buf		*bp;
18797 	struct	sd_xbuf		*xp;
18798 	int	err		= 0;
18799 	int	retry_count	= 0;
18800 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
18801 	struct	sd_sense_info	si;
18802 
18803 	ASSERT(pktp != NULL);
18804 	bp = (struct buf *)pktp->pkt_private;
18805 	ASSERT(bp != NULL);
18806 	xp = SD_GET_XBUF(bp);
18807 	ASSERT(xp != NULL);
18808 	un = SD_GET_UN(bp);
18809 	ASSERT(un != NULL);
18810 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18811 	ASSERT(un->un_f_monitor_media_state);
18812 
18813 	si.ssi_severity = SCSI_ERR_INFO;
18814 	si.ssi_pfa_flag = FALSE;
18815 
18816 	/*
18817 	 * When a reset is issued on a CDROM, it takes a long time to
18818 	 * recover. First few attempts to read capacity and other things
18819 	 * related to handling unit attention fail (with a ASC 0x4 and
18820 	 * ASCQ 0x1). In that case we want to do enough retries and we want
18821 	 * to limit the retries in other cases of genuine failures like
18822 	 * no media in drive.
18823 	 */
18824 	while (retry_count++ < retry_limit) {
18825 		if ((err = sd_handle_mchange(un)) == 0) {
18826 			break;
18827 		}
18828 		if (err == EAGAIN) {
18829 			retry_limit = SD_UNIT_ATTENTION_RETRY;
18830 		}
18831 		/* Sleep for 0.5 sec. & try again */
18832 		delay(drv_usectohz(500000));
18833 	}
18834 
18835 	/*
18836 	 * Dispatch (retry or fail) the original command here,
18837 	 * along with appropriate console messages....
18838 	 *
18839 	 * Must grab the mutex before calling sd_retry_command,
18840 	 * sd_print_sense_msg and sd_return_failed_command.
18841 	 */
18842 	mutex_enter(SD_MUTEX(un));
18843 	if (err != SD_CMD_SUCCESS) {
18844 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18845 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18846 		si.ssi_severity = SCSI_ERR_FATAL;
18847 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18848 		sd_return_failed_command(un, bp, EIO);
18849 	} else {
18850 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18851 		    &si, EIO, (clock_t)0, NULL);
18852 	}
18853 	mutex_exit(SD_MUTEX(un));
18854 }
18855 
18856 
18857 
18858 /*
18859  *    Function: sd_handle_mchange
18860  *
18861  * Description: Perform geometry validation & other recovery when CDROM
18862  *		has been removed from drive.
18863  *
18864  * Return Code: 0 for success
18865  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
18866  *		sd_send_scsi_READ_CAPACITY()
18867  *
18868  *     Context: Executes in a taskq() thread context
18869  */
18870 
18871 static int
18872 sd_handle_mchange(struct sd_lun *un)
18873 {
18874 	uint64_t	capacity;
18875 	uint32_t	lbasize;
18876 	int		rval;
18877 
18878 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18879 	ASSERT(un->un_f_monitor_media_state);
18880 
18881 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
18882 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
18883 		return (rval);
18884 	}
18885 
18886 	mutex_enter(SD_MUTEX(un));
18887 	sd_update_block_info(un, lbasize, capacity);
18888 
18889 	if (un->un_errstats != NULL) {
18890 		struct	sd_errstats *stp =
18891 		    (struct sd_errstats *)un->un_errstats->ks_data;
18892 		stp->sd_capacity.value.ui64 = (uint64_t)
18893 		    ((uint64_t)un->un_blockcount *
18894 		    (uint64_t)un->un_tgt_blocksize);
18895 	}
18896 
18897 	/*
18898 	 * Note: Maybe let the strategy/partitioning chain worry about getting
18899 	 * valid geometry.
18900 	 */
18901 	un->un_f_geometry_is_valid = FALSE;
18902 	(void) sd_validate_geometry(un, SD_PATH_DIRECT_PRIORITY);
18903 	if (un->un_f_geometry_is_valid == FALSE) {
18904 		mutex_exit(SD_MUTEX(un));
18905 		return (EIO);
18906 	}
18907 
18908 	mutex_exit(SD_MUTEX(un));
18909 
18910 	/*
18911 	 * Try to lock the door
18912 	 */
18913 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
18914 	    SD_PATH_DIRECT_PRIORITY));
18915 }
18916 
18917 
18918 /*
18919  *    Function: sd_send_scsi_DOORLOCK
18920  *
18921  * Description: Issue the scsi DOOR LOCK command
18922  *
18923  *   Arguments: un    - pointer to driver soft state (unit) structure for
18924  *			this target.
18925  *		flag  - SD_REMOVAL_ALLOW
18926  *			SD_REMOVAL_PREVENT
18927  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18928  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18929  *			to use the USCSI "direct" chain and bypass the normal
18930  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
18931  *			command is issued as part of an error recovery action.
18932  *
18933  * Return Code: 0   - Success
18934  *		errno return code from sd_send_scsi_cmd()
18935  *
18936  *     Context: Can sleep.
18937  */
18938 
18939 static int
18940 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
18941 {
18942 	union scsi_cdb		cdb;
18943 	struct uscsi_cmd	ucmd_buf;
18944 	struct scsi_extended_sense	sense_buf;
18945 	int			status;
18946 
18947 	ASSERT(un != NULL);
18948 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18949 
18950 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
18951 
18952 	/* already determined doorlock is not supported, fake success */
18953 	if (un->un_f_doorlock_supported == FALSE) {
18954 		return (0);
18955 	}
18956 
18957 	bzero(&cdb, sizeof (cdb));
18958 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18959 
18960 	cdb.scc_cmd = SCMD_DOORLOCK;
18961 	cdb.cdb_opaque[4] = (uchar_t)flag;
18962 
18963 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18964 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18965 	ucmd_buf.uscsi_bufaddr	= NULL;
18966 	ucmd_buf.uscsi_buflen	= 0;
18967 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18968 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
18969 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18970 	ucmd_buf.uscsi_timeout	= 15;
18971 
18972 	SD_TRACE(SD_LOG_IO, un,
18973 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
18974 
18975 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
18976 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
18977 
18978 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
18979 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18980 	    (sense_buf.es_key == KEY_ILLEGAL_REQUEST)) {
18981 		/* fake success and skip subsequent doorlock commands */
18982 		un->un_f_doorlock_supported = FALSE;
18983 		return (0);
18984 	}
18985 
18986 	return (status);
18987 }
18988 
18989 /*
18990  *    Function: sd_send_scsi_READ_CAPACITY
18991  *
18992  * Description: This routine uses the scsi READ CAPACITY command to determine
18993  *		the device capacity in number of blocks and the device native
18994  *		block size. If this function returns a failure, then the
18995  *		values in *capp and *lbap are undefined.  If the capacity
18996  *		returned is 0xffffffff then the lun is too large for a
18997  *		normal READ CAPACITY command and the results of a
18998  *		READ CAPACITY 16 will be used instead.
18999  *
19000  *   Arguments: un   - ptr to soft state struct for the target
19001  *		capp - ptr to unsigned 64-bit variable to receive the
19002  *			capacity value from the command.
19003  *		lbap - ptr to unsigned 32-bit varaible to receive the
19004  *			block size value from the command
19005  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19006  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19007  *			to use the USCSI "direct" chain and bypass the normal
19008  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19009  *			command is issued as part of an error recovery action.
19010  *
19011  * Return Code: 0   - Success
19012  *		EIO - IO error
19013  *		EACCES - Reservation conflict detected
19014  *		EAGAIN - Device is becoming ready
19015  *		errno return code from sd_send_scsi_cmd()
19016  *
19017  *     Context: Can sleep.  Blocks until command completes.
19018  */
19019 
19020 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
19021 
19022 static int
19023 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
19024 	int path_flag)
19025 {
19026 	struct	scsi_extended_sense	sense_buf;
19027 	struct	uscsi_cmd	ucmd_buf;
19028 	union	scsi_cdb	cdb;
19029 	uint32_t		*capacity_buf;
19030 	uint64_t		capacity;
19031 	uint32_t		lbasize;
19032 	int			status;
19033 
19034 	ASSERT(un != NULL);
19035 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19036 	ASSERT(capp != NULL);
19037 	ASSERT(lbap != NULL);
19038 
19039 	SD_TRACE(SD_LOG_IO, un,
19040 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19041 
19042 	/*
19043 	 * First send a READ_CAPACITY command to the target.
19044 	 * (This command is mandatory under SCSI-2.)
19045 	 *
19046 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
19047 	 * Medium Indicator bit is cleared.  The address field must be
19048 	 * zero if the PMI bit is zero.
19049 	 */
19050 	bzero(&cdb, sizeof (cdb));
19051 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19052 
19053 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
19054 
19055 	cdb.scc_cmd = SCMD_READ_CAPACITY;
19056 
19057 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19058 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19059 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
19060 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
19061 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19062 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19063 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19064 	ucmd_buf.uscsi_timeout	= 60;
19065 
19066 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19067 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
19068 
19069 	switch (status) {
19070 	case 0:
19071 		/* Return failure if we did not get valid capacity data. */
19072 		if (ucmd_buf.uscsi_resid != 0) {
19073 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19074 			return (EIO);
19075 		}
19076 
19077 		/*
19078 		 * Read capacity and block size from the READ CAPACITY 10 data.
19079 		 * This data may be adjusted later due to device specific
19080 		 * issues.
19081 		 *
19082 		 * According to the SCSI spec, the READ CAPACITY 10
19083 		 * command returns the following:
19084 		 *
19085 		 *  bytes 0-3: Maximum logical block address available.
19086 		 *		(MSB in byte:0 & LSB in byte:3)
19087 		 *
19088 		 *  bytes 4-7: Block length in bytes
19089 		 *		(MSB in byte:4 & LSB in byte:7)
19090 		 *
19091 		 */
19092 		capacity = BE_32(capacity_buf[0]);
19093 		lbasize = BE_32(capacity_buf[1]);
19094 
19095 		/*
19096 		 * Done with capacity_buf
19097 		 */
19098 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19099 
19100 		/*
19101 		 * if the reported capacity is set to all 0xf's, then
19102 		 * this disk is too large and requires SBC-2 commands.
19103 		 * Reissue the request using READ CAPACITY 16.
19104 		 */
19105 		if (capacity == 0xffffffff) {
19106 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
19107 			    &lbasize, path_flag);
19108 			if (status != 0) {
19109 				return (status);
19110 			}
19111 		}
19112 		break;	/* Success! */
19113 	case EIO:
19114 		switch (ucmd_buf.uscsi_status) {
19115 		case STATUS_RESERVATION_CONFLICT:
19116 			status = EACCES;
19117 			break;
19118 		case STATUS_CHECK:
19119 			/*
19120 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19121 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19122 			 */
19123 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19124 			    (sense_buf.es_add_code  == 0x04) &&
19125 			    (sense_buf.es_qual_code == 0x01)) {
19126 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19127 				return (EAGAIN);
19128 			}
19129 			break;
19130 		default:
19131 			break;
19132 		}
19133 		/* FALLTHRU */
19134 	default:
19135 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19136 		return (status);
19137 	}
19138 
19139 	/*
19140 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
19141 	 * (2352 and 0 are common) so for these devices always force the value
19142 	 * to 2048 as required by the ATAPI specs.
19143 	 */
19144 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
19145 		lbasize = 2048;
19146 	}
19147 
19148 	/*
19149 	 * Get the maximum LBA value from the READ CAPACITY data.
19150 	 * Here we assume that the Partial Medium Indicator (PMI) bit
19151 	 * was cleared when issuing the command. This means that the LBA
19152 	 * returned from the device is the LBA of the last logical block
19153 	 * on the logical unit.  The actual logical block count will be
19154 	 * this value plus one.
19155 	 *
19156 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
19157 	 * so scale the capacity value to reflect this.
19158 	 */
19159 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
19160 
19161 #if defined(__i386) || defined(__amd64)
19162 	/*
19163 	 * On x86, compensate for off-by-1 error (number of sectors on
19164 	 * media)  (1175930)
19165 	 */
19166 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
19167 	    (lbasize == un->un_sys_blocksize)) {
19168 		capacity -= 1;
19169 	}
19170 #endif
19171 
19172 	/*
19173 	 * Copy the values from the READ CAPACITY command into the space
19174 	 * provided by the caller.
19175 	 */
19176 	*capp = capacity;
19177 	*lbap = lbasize;
19178 
19179 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
19180 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19181 
19182 	/*
19183 	 * Both the lbasize and capacity from the device must be nonzero,
19184 	 * otherwise we assume that the values are not valid and return
19185 	 * failure to the caller. (4203735)
19186 	 */
19187 	if ((capacity == 0) || (lbasize == 0)) {
19188 		return (EIO);
19189 	}
19190 
19191 	return (0);
19192 }
19193 
19194 /*
19195  *    Function: sd_send_scsi_READ_CAPACITY_16
19196  *
19197  * Description: This routine uses the scsi READ CAPACITY 16 command to
19198  *		determine the device capacity in number of blocks and the
19199  *		device native block size.  If this function returns a failure,
19200  *		then the values in *capp and *lbap are undefined.
19201  *		This routine should always be called by
19202  *		sd_send_scsi_READ_CAPACITY which will appy any device
19203  *		specific adjustments to capacity and lbasize.
19204  *
19205  *   Arguments: un   - ptr to soft state struct for the target
19206  *		capp - ptr to unsigned 64-bit variable to receive the
19207  *			capacity value from the command.
19208  *		lbap - ptr to unsigned 32-bit varaible to receive the
19209  *			block size value from the command
19210  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19211  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19212  *			to use the USCSI "direct" chain and bypass the normal
19213  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
19214  *			this command is issued as part of an error recovery
19215  *			action.
19216  *
19217  * Return Code: 0   - Success
19218  *		EIO - IO error
19219  *		EACCES - Reservation conflict detected
19220  *		EAGAIN - Device is becoming ready
19221  *		errno return code from sd_send_scsi_cmd()
19222  *
19223  *     Context: Can sleep.  Blocks until command completes.
19224  */
19225 
19226 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
19227 
19228 static int
19229 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
19230 	uint32_t *lbap, int path_flag)
19231 {
19232 	struct	scsi_extended_sense	sense_buf;
19233 	struct	uscsi_cmd	ucmd_buf;
19234 	union	scsi_cdb	cdb;
19235 	uint64_t		*capacity16_buf;
19236 	uint64_t		capacity;
19237 	uint32_t		lbasize;
19238 	int			status;
19239 
19240 	ASSERT(un != NULL);
19241 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19242 	ASSERT(capp != NULL);
19243 	ASSERT(lbap != NULL);
19244 
19245 	SD_TRACE(SD_LOG_IO, un,
19246 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19247 
19248 	/*
19249 	 * First send a READ_CAPACITY_16 command to the target.
19250 	 *
19251 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
19252 	 * Medium Indicator bit is cleared.  The address field must be
19253 	 * zero if the PMI bit is zero.
19254 	 */
19255 	bzero(&cdb, sizeof (cdb));
19256 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19257 
19258 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
19259 
19260 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19261 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
19262 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
19263 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
19264 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19265 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19266 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19267 	ucmd_buf.uscsi_timeout	= 60;
19268 
19269 	/*
19270 	 * Read Capacity (16) is a Service Action In command.  One
19271 	 * command byte (0x9E) is overloaded for multiple operations,
19272 	 * with the second CDB byte specifying the desired operation
19273 	 */
19274 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
19275 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
19276 
19277 	/*
19278 	 * Fill in allocation length field
19279 	 */
19280 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
19281 
19282 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19283 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
19284 
19285 	switch (status) {
19286 	case 0:
19287 		/* Return failure if we did not get valid capacity data. */
19288 		if (ucmd_buf.uscsi_resid > 20) {
19289 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19290 			return (EIO);
19291 		}
19292 
19293 		/*
19294 		 * Read capacity and block size from the READ CAPACITY 10 data.
19295 		 * This data may be adjusted later due to device specific
19296 		 * issues.
19297 		 *
19298 		 * According to the SCSI spec, the READ CAPACITY 10
19299 		 * command returns the following:
19300 		 *
19301 		 *  bytes 0-7: Maximum logical block address available.
19302 		 *		(MSB in byte:0 & LSB in byte:7)
19303 		 *
19304 		 *  bytes 8-11: Block length in bytes
19305 		 *		(MSB in byte:8 & LSB in byte:11)
19306 		 *
19307 		 */
19308 		capacity = BE_64(capacity16_buf[0]);
19309 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
19310 
19311 		/*
19312 		 * Done with capacity16_buf
19313 		 */
19314 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19315 
19316 		/*
19317 		 * if the reported capacity is set to all 0xf's, then
19318 		 * this disk is too large.  This could only happen with
19319 		 * a device that supports LBAs larger than 64 bits which
19320 		 * are not defined by any current T10 standards.
19321 		 */
19322 		if (capacity == 0xffffffffffffffff) {
19323 			return (EIO);
19324 		}
19325 		break;	/* Success! */
19326 	case EIO:
19327 		switch (ucmd_buf.uscsi_status) {
19328 		case STATUS_RESERVATION_CONFLICT:
19329 			status = EACCES;
19330 			break;
19331 		case STATUS_CHECK:
19332 			/*
19333 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19334 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19335 			 */
19336 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19337 			    (sense_buf.es_add_code  == 0x04) &&
19338 			    (sense_buf.es_qual_code == 0x01)) {
19339 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19340 				return (EAGAIN);
19341 			}
19342 			break;
19343 		default:
19344 			break;
19345 		}
19346 		/* FALLTHRU */
19347 	default:
19348 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19349 		return (status);
19350 	}
19351 
19352 	*capp = capacity;
19353 	*lbap = lbasize;
19354 
19355 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
19356 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19357 
19358 	return (0);
19359 }
19360 
19361 
19362 /*
19363  *    Function: sd_send_scsi_START_STOP_UNIT
19364  *
19365  * Description: Issue a scsi START STOP UNIT command to the target.
19366  *
19367  *   Arguments: un    - pointer to driver soft state (unit) structure for
19368  *			this target.
19369  *		flag  - SD_TARGET_START
19370  *			SD_TARGET_STOP
19371  *			SD_TARGET_EJECT
19372  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19373  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19374  *			to use the USCSI "direct" chain and bypass the normal
19375  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19376  *			command is issued as part of an error recovery action.
19377  *
19378  * Return Code: 0   - Success
19379  *		EIO - IO error
19380  *		EACCES - Reservation conflict detected
19381  *		ENXIO  - Not Ready, medium not present
19382  *		errno return code from sd_send_scsi_cmd()
19383  *
19384  *     Context: Can sleep.
19385  */
19386 
19387 static int
19388 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
19389 {
19390 	struct	scsi_extended_sense	sense_buf;
19391 	union scsi_cdb		cdb;
19392 	struct uscsi_cmd	ucmd_buf;
19393 	int			status;
19394 
19395 	ASSERT(un != NULL);
19396 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19397 
19398 	SD_TRACE(SD_LOG_IO, un,
19399 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
19400 
19401 	if (un->un_f_check_start_stop &&
19402 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
19403 	    (un->un_f_start_stop_supported != TRUE)) {
19404 		return (0);
19405 	}
19406 
19407 	bzero(&cdb, sizeof (cdb));
19408 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19409 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19410 
19411 	cdb.scc_cmd = SCMD_START_STOP;
19412 	cdb.cdb_opaque[4] = (uchar_t)flag;
19413 
19414 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19415 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19416 	ucmd_buf.uscsi_bufaddr	= NULL;
19417 	ucmd_buf.uscsi_buflen	= 0;
19418 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19419 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19420 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19421 	ucmd_buf.uscsi_timeout	= 200;
19422 
19423 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19424 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
19425 
19426 	switch (status) {
19427 	case 0:
19428 		break;	/* Success! */
19429 	case EIO:
19430 		switch (ucmd_buf.uscsi_status) {
19431 		case STATUS_RESERVATION_CONFLICT:
19432 			status = EACCES;
19433 			break;
19434 		case STATUS_CHECK:
19435 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
19436 				switch (sense_buf.es_key) {
19437 				case KEY_ILLEGAL_REQUEST:
19438 					status = ENOTSUP;
19439 					break;
19440 				case KEY_NOT_READY:
19441 					if (sense_buf.es_add_code == 0x3A) {
19442 						status = ENXIO;
19443 					}
19444 					break;
19445 				default:
19446 					break;
19447 				}
19448 			}
19449 			break;
19450 		default:
19451 			break;
19452 		}
19453 		break;
19454 	default:
19455 		break;
19456 	}
19457 
19458 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
19459 
19460 	return (status);
19461 }
19462 
19463 
19464 /*
19465  *    Function: sd_start_stop_unit_callback
19466  *
19467  * Description: timeout(9F) callback to begin recovery process for a
19468  *		device that has spun down.
19469  *
19470  *   Arguments: arg - pointer to associated softstate struct.
19471  *
19472  *     Context: Executes in a timeout(9F) thread context
19473  */
19474 
19475 static void
19476 sd_start_stop_unit_callback(void *arg)
19477 {
19478 	struct sd_lun	*un = arg;
19479 	ASSERT(un != NULL);
19480 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19481 
19482 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
19483 
19484 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
19485 }
19486 
19487 
19488 /*
19489  *    Function: sd_start_stop_unit_task
19490  *
19491  * Description: Recovery procedure when a drive is spun down.
19492  *
19493  *   Arguments: arg - pointer to associated softstate struct.
19494  *
19495  *     Context: Executes in a taskq() thread context
19496  */
19497 
19498 static void
19499 sd_start_stop_unit_task(void *arg)
19500 {
19501 	struct sd_lun	*un = arg;
19502 
19503 	ASSERT(un != NULL);
19504 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19505 
19506 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
19507 
19508 	/*
19509 	 * Some unformatted drives report not ready error, no need to
19510 	 * restart if format has been initiated.
19511 	 */
19512 	mutex_enter(SD_MUTEX(un));
19513 	if (un->un_f_format_in_progress == TRUE) {
19514 		mutex_exit(SD_MUTEX(un));
19515 		return;
19516 	}
19517 	mutex_exit(SD_MUTEX(un));
19518 
19519 	/*
19520 	 * When a START STOP command is issued from here, it is part of a
19521 	 * failure recovery operation and must be issued before any other
19522 	 * commands, including any pending retries. Thus it must be sent
19523 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
19524 	 * succeeds or not, we will start I/O after the attempt.
19525 	 */
19526 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
19527 	    SD_PATH_DIRECT_PRIORITY);
19528 
19529 	/*
19530 	 * The above call blocks until the START_STOP_UNIT command completes.
19531 	 * Now that it has completed, we must re-try the original IO that
19532 	 * received the NOT READY condition in the first place. There are
19533 	 * three possible conditions here:
19534 	 *
19535 	 *  (1) The original IO is on un_retry_bp.
19536 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
19537 	 *	is NULL.
19538 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
19539 	 *	points to some other, unrelated bp.
19540 	 *
19541 	 * For each case, we must call sd_start_cmds() with un_retry_bp
19542 	 * as the argument. If un_retry_bp is NULL, this will initiate
19543 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
19544 	 * then this will process the bp on un_retry_bp. That may or may not
19545 	 * be the original IO, but that does not matter: the important thing
19546 	 * is to keep the IO processing going at this point.
19547 	 *
19548 	 * Note: This is a very specific error recovery sequence associated
19549 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
19550 	 * serialize the I/O with completion of the spin-up.
19551 	 */
19552 	mutex_enter(SD_MUTEX(un));
19553 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19554 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
19555 	    un, un->un_retry_bp);
19556 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
19557 	sd_start_cmds(un, un->un_retry_bp);
19558 	mutex_exit(SD_MUTEX(un));
19559 
19560 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
19561 }
19562 
19563 
19564 /*
19565  *    Function: sd_send_scsi_INQUIRY
19566  *
19567  * Description: Issue the scsi INQUIRY command.
19568  *
19569  *   Arguments: un
19570  *		bufaddr
19571  *		buflen
19572  *		evpd
19573  *		page_code
19574  *		page_length
19575  *
19576  * Return Code: 0   - Success
19577  *		errno return code from sd_send_scsi_cmd()
19578  *
19579  *     Context: Can sleep. Does not return until command is completed.
19580  */
19581 
19582 static int
19583 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
19584 	uchar_t evpd, uchar_t page_code, size_t *residp)
19585 {
19586 	union scsi_cdb		cdb;
19587 	struct uscsi_cmd	ucmd_buf;
19588 	int			status;
19589 
19590 	ASSERT(un != NULL);
19591 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19592 	ASSERT(bufaddr != NULL);
19593 
19594 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
19595 
19596 	bzero(&cdb, sizeof (cdb));
19597 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19598 	bzero(bufaddr, buflen);
19599 
19600 	cdb.scc_cmd = SCMD_INQUIRY;
19601 	cdb.cdb_opaque[1] = evpd;
19602 	cdb.cdb_opaque[2] = page_code;
19603 	FORMG0COUNT(&cdb, buflen);
19604 
19605 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19606 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19607 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19608 	ucmd_buf.uscsi_buflen	= buflen;
19609 	ucmd_buf.uscsi_rqbuf	= NULL;
19610 	ucmd_buf.uscsi_rqlen	= 0;
19611 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
19612 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
19613 
19614 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19615 	    UIO_SYSSPACE, UIO_SYSSPACE, SD_PATH_DIRECT);
19616 
19617 	if ((status == 0) && (residp != NULL)) {
19618 		*residp = ucmd_buf.uscsi_resid;
19619 	}
19620 
19621 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
19622 
19623 	return (status);
19624 }
19625 
19626 
19627 /*
19628  *    Function: sd_send_scsi_TEST_UNIT_READY
19629  *
19630  * Description: Issue the scsi TEST UNIT READY command.
19631  *		This routine can be told to set the flag USCSI_DIAGNOSE to
19632  *		prevent retrying failed commands. Use this when the intent
19633  *		is either to check for device readiness, to clear a Unit
19634  *		Attention, or to clear any outstanding sense data.
19635  *		However under specific conditions the expected behavior
19636  *		is for retries to bring a device ready, so use the flag
19637  *		with caution.
19638  *
19639  *   Arguments: un
19640  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
19641  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
19642  *			0: dont check for media present, do retries on cmd.
19643  *
19644  * Return Code: 0   - Success
19645  *		EIO - IO error
19646  *		EACCES - Reservation conflict detected
19647  *		ENXIO  - Not Ready, medium not present
19648  *		errno return code from sd_send_scsi_cmd()
19649  *
19650  *     Context: Can sleep. Does not return until command is completed.
19651  */
19652 
19653 static int
19654 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
19655 {
19656 	struct	scsi_extended_sense	sense_buf;
19657 	union scsi_cdb		cdb;
19658 	struct uscsi_cmd	ucmd_buf;
19659 	int			status;
19660 
19661 	ASSERT(un != NULL);
19662 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19663 
19664 	SD_TRACE(SD_LOG_IO, un,
19665 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
19666 
19667 	/*
19668 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
19669 	 * timeouts when they receive a TUR and the queue is not empty. Check
19670 	 * the configuration flag set during attach (indicating the drive has
19671 	 * this firmware bug) and un_ncmds_in_transport before issuing the
19672 	 * TUR. If there are
19673 	 * pending commands return success, this is a bit arbitrary but is ok
19674 	 * for non-removables (i.e. the eliteI disks) and non-clustering
19675 	 * configurations.
19676 	 */
19677 	if (un->un_f_cfg_tur_check == TRUE) {
19678 		mutex_enter(SD_MUTEX(un));
19679 		if (un->un_ncmds_in_transport != 0) {
19680 			mutex_exit(SD_MUTEX(un));
19681 			return (0);
19682 		}
19683 		mutex_exit(SD_MUTEX(un));
19684 	}
19685 
19686 	bzero(&cdb, sizeof (cdb));
19687 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19688 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19689 
19690 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
19691 
19692 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19693 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19694 	ucmd_buf.uscsi_bufaddr	= NULL;
19695 	ucmd_buf.uscsi_buflen	= 0;
19696 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19697 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19698 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19699 
19700 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
19701 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
19702 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
19703 	}
19704 	ucmd_buf.uscsi_timeout	= 60;
19705 
19706 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19707 	    UIO_SYSSPACE, UIO_SYSSPACE,
19708 	    ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT : SD_PATH_STANDARD));
19709 
19710 	switch (status) {
19711 	case 0:
19712 		break;	/* Success! */
19713 	case EIO:
19714 		switch (ucmd_buf.uscsi_status) {
19715 		case STATUS_RESERVATION_CONFLICT:
19716 			status = EACCES;
19717 			break;
19718 		case STATUS_CHECK:
19719 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
19720 				break;
19721 			}
19722 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19723 			    (sense_buf.es_key == KEY_NOT_READY) &&
19724 			    (sense_buf.es_add_code == 0x3A)) {
19725 				status = ENXIO;
19726 			}
19727 			break;
19728 		default:
19729 			break;
19730 		}
19731 		break;
19732 	default:
19733 		break;
19734 	}
19735 
19736 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
19737 
19738 	return (status);
19739 }
19740 
19741 
19742 /*
19743  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
19744  *
19745  * Description: Issue the scsi PERSISTENT RESERVE IN command.
19746  *
19747  *   Arguments: un
19748  *
19749  * Return Code: 0   - Success
19750  *		EACCES
19751  *		ENOTSUP
19752  *		errno return code from sd_send_scsi_cmd()
19753  *
19754  *     Context: Can sleep. Does not return until command is completed.
19755  */
19756 
19757 static int
19758 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
19759 	uint16_t data_len, uchar_t *data_bufp)
19760 {
19761 	struct scsi_extended_sense	sense_buf;
19762 	union scsi_cdb		cdb;
19763 	struct uscsi_cmd	ucmd_buf;
19764 	int			status;
19765 	int			no_caller_buf = FALSE;
19766 
19767 	ASSERT(un != NULL);
19768 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19769 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
19770 
19771 	SD_TRACE(SD_LOG_IO, un,
19772 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
19773 
19774 	bzero(&cdb, sizeof (cdb));
19775 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19776 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19777 	if (data_bufp == NULL) {
19778 		/* Allocate a default buf if the caller did not give one */
19779 		ASSERT(data_len == 0);
19780 		data_len  = MHIOC_RESV_KEY_SIZE;
19781 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
19782 		no_caller_buf = TRUE;
19783 	}
19784 
19785 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
19786 	cdb.cdb_opaque[1] = usr_cmd;
19787 	FORMG1COUNT(&cdb, data_len);
19788 
19789 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19790 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19791 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
19792 	ucmd_buf.uscsi_buflen	= data_len;
19793 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19794 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19795 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19796 	ucmd_buf.uscsi_timeout	= 60;
19797 
19798 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19799 	    UIO_SYSSPACE, UIO_SYSSPACE, SD_PATH_STANDARD);
19800 
19801 	switch (status) {
19802 	case 0:
19803 		break;	/* Success! */
19804 	case EIO:
19805 		switch (ucmd_buf.uscsi_status) {
19806 		case STATUS_RESERVATION_CONFLICT:
19807 			status = EACCES;
19808 			break;
19809 		case STATUS_CHECK:
19810 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19811 			    (sense_buf.es_key == KEY_ILLEGAL_REQUEST)) {
19812 				status = ENOTSUP;
19813 			}
19814 			break;
19815 		default:
19816 			break;
19817 		}
19818 		break;
19819 	default:
19820 		break;
19821 	}
19822 
19823 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
19824 
19825 	if (no_caller_buf == TRUE) {
19826 		kmem_free(data_bufp, data_len);
19827 	}
19828 
19829 	return (status);
19830 }
19831 
19832 
19833 /*
19834  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
19835  *
19836  * Description: This routine is the driver entry point for handling CD-ROM
19837  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
19838  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
19839  *		device.
19840  *
19841  *   Arguments: un  -   Pointer to soft state struct for the target.
19842  *		usr_cmd SCSI-3 reservation facility command (one of
19843  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
19844  *			SD_SCSI3_PREEMPTANDABORT)
19845  *		usr_bufp - user provided pointer register, reserve descriptor or
19846  *			preempt and abort structure (mhioc_register_t,
19847  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
19848  *
19849  * Return Code: 0   - Success
19850  *		EACCES
19851  *		ENOTSUP
19852  *		errno return code from sd_send_scsi_cmd()
19853  *
19854  *     Context: Can sleep. Does not return until command is completed.
19855  */
19856 
19857 static int
19858 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
19859 	uchar_t	*usr_bufp)
19860 {
19861 	struct scsi_extended_sense	sense_buf;
19862 	union scsi_cdb		cdb;
19863 	struct uscsi_cmd	ucmd_buf;
19864 	int			status;
19865 	uchar_t			data_len = sizeof (sd_prout_t);
19866 	sd_prout_t		*prp;
19867 
19868 	ASSERT(un != NULL);
19869 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19870 	ASSERT(data_len == 24);	/* required by scsi spec */
19871 
19872 	SD_TRACE(SD_LOG_IO, un,
19873 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
19874 
19875 	if (usr_bufp == NULL) {
19876 		return (EINVAL);
19877 	}
19878 
19879 	bzero(&cdb, sizeof (cdb));
19880 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19881 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19882 	prp = kmem_zalloc(data_len, KM_SLEEP);
19883 
19884 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
19885 	cdb.cdb_opaque[1] = usr_cmd;
19886 	FORMG1COUNT(&cdb, data_len);
19887 
19888 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19889 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19890 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
19891 	ucmd_buf.uscsi_buflen	= data_len;
19892 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19893 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19894 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
19895 	ucmd_buf.uscsi_timeout	= 60;
19896 
19897 	switch (usr_cmd) {
19898 	case SD_SCSI3_REGISTER: {
19899 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
19900 
19901 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
19902 		bcopy(ptr->newkey.key, prp->service_key,
19903 		    MHIOC_RESV_KEY_SIZE);
19904 		prp->aptpl = ptr->aptpl;
19905 		break;
19906 	}
19907 	case SD_SCSI3_RESERVE:
19908 	case SD_SCSI3_RELEASE: {
19909 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
19910 
19911 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
19912 		prp->scope_address = BE_32(ptr->scope_specific_addr);
19913 		cdb.cdb_opaque[2] = ptr->type;
19914 		break;
19915 	}
19916 	case SD_SCSI3_PREEMPTANDABORT: {
19917 		mhioc_preemptandabort_t *ptr =
19918 		    (mhioc_preemptandabort_t *)usr_bufp;
19919 
19920 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
19921 		bcopy(ptr->victim_key.key, prp->service_key,
19922 		    MHIOC_RESV_KEY_SIZE);
19923 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
19924 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
19925 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
19926 		break;
19927 	}
19928 	case SD_SCSI3_REGISTERANDIGNOREKEY:
19929 	{
19930 		mhioc_registerandignorekey_t *ptr;
19931 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
19932 		bcopy(ptr->newkey.key,
19933 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
19934 		prp->aptpl = ptr->aptpl;
19935 		break;
19936 	}
19937 	default:
19938 		ASSERT(FALSE);
19939 		break;
19940 	}
19941 
19942 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
19943 	    UIO_SYSSPACE, UIO_SYSSPACE, SD_PATH_STANDARD);
19944 
19945 	switch (status) {
19946 	case 0:
19947 		break;	/* Success! */
19948 	case EIO:
19949 		switch (ucmd_buf.uscsi_status) {
19950 		case STATUS_RESERVATION_CONFLICT:
19951 			status = EACCES;
19952 			break;
19953 		case STATUS_CHECK:
19954 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19955 			    (sense_buf.es_key == KEY_ILLEGAL_REQUEST)) {
19956 				status = ENOTSUP;
19957 			}
19958 			break;
19959 		default:
19960 			break;
19961 		}
19962 		break;
19963 	default:
19964 		break;
19965 	}
19966 
19967 	kmem_free(prp, data_len);
19968 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
19969 	return (status);
19970 }
19971 
19972 
19973 /*
19974  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
19975  *
19976  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
19977  *
19978  *   Arguments: un - pointer to the target's soft state struct
19979  *
19980  * Return Code: 0 - success
19981  *		errno-type error code
19982  *
19983  *     Context: kernel thread context only.
19984  */
19985 
19986 static int
19987 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
19988 {
19989 	struct sd_uscsi_info	*uip;
19990 	struct uscsi_cmd	*uscmd;
19991 	union scsi_cdb		*cdb;
19992 	struct buf		*bp;
19993 	int			rval = 0;
19994 
19995 	SD_TRACE(SD_LOG_IO, un,
19996 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
19997 
19998 	ASSERT(un != NULL);
19999 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20000 
20001 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
20002 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
20003 
20004 	/*
20005 	 * First get some memory for the uscsi_cmd struct and cdb
20006 	 * and initialize for SYNCHRONIZE_CACHE cmd.
20007 	 */
20008 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
20009 	uscmd->uscsi_cdblen = CDB_GROUP1;
20010 	uscmd->uscsi_cdb = (caddr_t)cdb;
20011 	uscmd->uscsi_bufaddr = NULL;
20012 	uscmd->uscsi_buflen = 0;
20013 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20014 	uscmd->uscsi_rqlen = SENSE_LENGTH;
20015 	uscmd->uscsi_rqresid = SENSE_LENGTH;
20016 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
20017 	uscmd->uscsi_timeout = sd_io_time;
20018 
20019 	/*
20020 	 * Allocate an sd_uscsi_info struct and fill it with the info
20021 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
20022 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
20023 	 * since we allocate the buf here in this function, we do not
20024 	 * need to preserve the prior contents of b_private.
20025 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
20026 	 */
20027 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
20028 	uip->ui_flags = SD_PATH_DIRECT;
20029 	uip->ui_cmdp  = uscmd;
20030 
20031 	bp = getrbuf(KM_SLEEP);
20032 	bp->b_private = uip;
20033 
20034 	/*
20035 	 * Setup buffer to carry uscsi request.
20036 	 */
20037 	bp->b_flags  = B_BUSY;
20038 	bp->b_bcount = 0;
20039 	bp->b_blkno  = 0;
20040 
20041 	if (dkc != NULL) {
20042 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
20043 		uip->ui_dkc = *dkc;
20044 	}
20045 
20046 	bp->b_edev = SD_GET_DEV(un);
20047 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
20048 
20049 	(void) sd_uscsi_strategy(bp);
20050 
20051 	/*
20052 	 * If synchronous request, wait for completion
20053 	 * If async just return and let b_iodone callback
20054 	 * cleanup.
20055 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
20056 	 * but it was also incremented in sd_uscsi_strategy(), so
20057 	 * we should be ok.
20058 	 */
20059 	if (dkc == NULL) {
20060 		(void) biowait(bp);
20061 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
20062 	}
20063 
20064 	return (rval);
20065 }
20066 
20067 
20068 static int
20069 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
20070 {
20071 	struct sd_uscsi_info *uip;
20072 	struct uscsi_cmd *uscmd;
20073 	struct scsi_extended_sense *sense_buf;
20074 	struct sd_lun *un;
20075 	int status;
20076 
20077 	uip = (struct sd_uscsi_info *)(bp->b_private);
20078 	ASSERT(uip != NULL);
20079 
20080 	uscmd = uip->ui_cmdp;
20081 	ASSERT(uscmd != NULL);
20082 
20083 	sense_buf = (struct scsi_extended_sense *)uscmd->uscsi_rqbuf;
20084 	ASSERT(sense_buf != NULL);
20085 
20086 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
20087 	ASSERT(un != NULL);
20088 
20089 	status = geterror(bp);
20090 	switch (status) {
20091 	case 0:
20092 		break;	/* Success! */
20093 	case EIO:
20094 		switch (uscmd->uscsi_status) {
20095 		case STATUS_RESERVATION_CONFLICT:
20096 			/* Ignore reservation conflict */
20097 			status = 0;
20098 			goto done;
20099 
20100 		case STATUS_CHECK:
20101 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
20102 			    (sense_buf->es_key == KEY_ILLEGAL_REQUEST)) {
20103 				/* Ignore Illegal Request error */
20104 				mutex_enter(SD_MUTEX(un));
20105 				un->un_f_sync_cache_supported = FALSE;
20106 				mutex_exit(SD_MUTEX(un));
20107 				status = ENOTSUP;
20108 				goto done;
20109 			}
20110 			break;
20111 		default:
20112 			break;
20113 		}
20114 		/* FALLTHRU */
20115 	default:
20116 		/* Ignore error if the media is not present */
20117 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
20118 			status = 0;
20119 			goto done;
20120 		}
20121 		/* If we reach this, we had an error */
20122 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
20123 		    "SYNCHRONIZE CACHE command failed (%d)\n", status);
20124 		break;
20125 	}
20126 
20127 done:
20128 	if (uip->ui_dkc.dkc_callback != NULL) {
20129 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
20130 	}
20131 
20132 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
20133 	freerbuf(bp);
20134 	kmem_free(uip, sizeof (struct sd_uscsi_info));
20135 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
20136 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
20137 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
20138 
20139 	return (status);
20140 }
20141 
20142 
20143 /*
20144  *    Function: sd_send_scsi_GET_CONFIGURATION
20145  *
20146  * Description: Issues the get configuration command to the device.
20147  *		Called from sd_check_for_writable_cd & sd_get_media_info
20148  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
20149  *   Arguments: un
20150  *		ucmdbuf
20151  *		rqbuf
20152  *		rqbuflen
20153  *		bufaddr
20154  *		buflen
20155  *
20156  * Return Code: 0   - Success
20157  *		errno return code from sd_send_scsi_cmd()
20158  *
20159  *     Context: Can sleep. Does not return until command is completed.
20160  *
20161  */
20162 
20163 static int
20164 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
20165 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen)
20166 {
20167 	char	cdb[CDB_GROUP1];
20168 	int	status;
20169 
20170 	ASSERT(un != NULL);
20171 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20172 	ASSERT(bufaddr != NULL);
20173 	ASSERT(ucmdbuf != NULL);
20174 	ASSERT(rqbuf != NULL);
20175 
20176 	SD_TRACE(SD_LOG_IO, un,
20177 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
20178 
20179 	bzero(cdb, sizeof (cdb));
20180 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
20181 	bzero(rqbuf, rqbuflen);
20182 	bzero(bufaddr, buflen);
20183 
20184 	/*
20185 	 * Set up cdb field for the get configuration command.
20186 	 */
20187 	cdb[0] = SCMD_GET_CONFIGURATION;
20188 	cdb[1] = 0x02;  /* Requested Type */
20189 	cdb[8] = SD_PROFILE_HEADER_LEN;
20190 	ucmdbuf->uscsi_cdb = cdb;
20191 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
20192 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
20193 	ucmdbuf->uscsi_buflen = buflen;
20194 	ucmdbuf->uscsi_timeout = sd_io_time;
20195 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
20196 	ucmdbuf->uscsi_rqlen = rqbuflen;
20197 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
20198 
20199 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, UIO_SYSSPACE,
20200 	    UIO_SYSSPACE, UIO_SYSSPACE, SD_PATH_STANDARD);
20201 
20202 	switch (status) {
20203 	case 0:
20204 		break;  /* Success! */
20205 	case EIO:
20206 		switch (ucmdbuf->uscsi_status) {
20207 		case STATUS_RESERVATION_CONFLICT:
20208 			status = EACCES;
20209 			break;
20210 		default:
20211 			break;
20212 		}
20213 		break;
20214 	default:
20215 		break;
20216 	}
20217 
20218 	if (status == 0) {
20219 		SD_DUMP_MEMORY(un, SD_LOG_IO,
20220 		    "sd_send_scsi_GET_CONFIGURATION: data",
20221 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
20222 	}
20223 
20224 	SD_TRACE(SD_LOG_IO, un,
20225 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
20226 
20227 	return (status);
20228 }
20229 
20230 /*
20231  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
20232  *
20233  * Description: Issues the get configuration command to the device to
20234  *              retrieve a specfic feature. Called from
20235  *		sd_check_for_writable_cd & sd_set_mmc_caps.
20236  *   Arguments: un
20237  *              ucmdbuf
20238  *              rqbuf
20239  *              rqbuflen
20240  *              bufaddr
20241  *              buflen
20242  *		feature
20243  *
20244  * Return Code: 0   - Success
20245  *              errno return code from sd_send_scsi_cmd()
20246  *
20247  *     Context: Can sleep. Does not return until command is completed.
20248  *
20249  */
20250 static int
20251 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
20252 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
20253 	uchar_t *bufaddr, uint_t buflen, char feature)
20254 {
20255 	char    cdb[CDB_GROUP1];
20256 	int	status;
20257 
20258 	ASSERT(un != NULL);
20259 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20260 	ASSERT(bufaddr != NULL);
20261 	ASSERT(ucmdbuf != NULL);
20262 	ASSERT(rqbuf != NULL);
20263 
20264 	SD_TRACE(SD_LOG_IO, un,
20265 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
20266 
20267 	bzero(cdb, sizeof (cdb));
20268 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
20269 	bzero(rqbuf, rqbuflen);
20270 	bzero(bufaddr, buflen);
20271 
20272 	/*
20273 	 * Set up cdb field for the get configuration command.
20274 	 */
20275 	cdb[0] = SCMD_GET_CONFIGURATION;
20276 	cdb[1] = 0x02;  /* Requested Type */
20277 	cdb[3] = feature;
20278 	cdb[8] = buflen;
20279 	ucmdbuf->uscsi_cdb = cdb;
20280 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
20281 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
20282 	ucmdbuf->uscsi_buflen = buflen;
20283 	ucmdbuf->uscsi_timeout = sd_io_time;
20284 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
20285 	ucmdbuf->uscsi_rqlen = rqbuflen;
20286 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
20287 
20288 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, UIO_SYSSPACE,
20289 	    UIO_SYSSPACE, UIO_SYSSPACE, SD_PATH_STANDARD);
20290 
20291 	switch (status) {
20292 	case 0:
20293 		break;  /* Success! */
20294 	case EIO:
20295 		switch (ucmdbuf->uscsi_status) {
20296 		case STATUS_RESERVATION_CONFLICT:
20297 			status = EACCES;
20298 			break;
20299 		default:
20300 			break;
20301 		}
20302 		break;
20303 	default:
20304 		break;
20305 	}
20306 
20307 	if (status == 0) {
20308 		SD_DUMP_MEMORY(un, SD_LOG_IO,
20309 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
20310 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
20311 	}
20312 
20313 	SD_TRACE(SD_LOG_IO, un,
20314 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
20315 
20316 	return (status);
20317 }
20318 
20319 
20320 /*
20321  *    Function: sd_send_scsi_MODE_SENSE
20322  *
20323  * Description: Utility function for issuing a scsi MODE SENSE command.
20324  *		Note: This routine uses a consistent implementation for Group0,
20325  *		Group1, and Group2 commands across all platforms. ATAPI devices
20326  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
20327  *
20328  *   Arguments: un - pointer to the softstate struct for the target.
20329  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
20330  *			  CDB_GROUP[1|2] (10 byte).
20331  *		bufaddr - buffer for page data retrieved from the target.
20332  *		buflen - size of page to be retrieved.
20333  *		page_code - page code of data to be retrieved from the target.
20334  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20335  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20336  *			to use the USCSI "direct" chain and bypass the normal
20337  *			command waitq.
20338  *
20339  * Return Code: 0   - Success
20340  *		errno return code from sd_send_scsi_cmd()
20341  *
20342  *     Context: Can sleep. Does not return until command is completed.
20343  */
20344 
20345 static int
20346 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
20347 	size_t buflen,  uchar_t page_code, int path_flag)
20348 {
20349 	struct	scsi_extended_sense	sense_buf;
20350 	union scsi_cdb		cdb;
20351 	struct uscsi_cmd	ucmd_buf;
20352 	int			status;
20353 
20354 	ASSERT(un != NULL);
20355 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20356 	ASSERT(bufaddr != NULL);
20357 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
20358 	    (cdbsize == CDB_GROUP2));
20359 
20360 	SD_TRACE(SD_LOG_IO, un,
20361 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
20362 
20363 	bzero(&cdb, sizeof (cdb));
20364 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20365 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20366 	bzero(bufaddr, buflen);
20367 
20368 	if (cdbsize == CDB_GROUP0) {
20369 		cdb.scc_cmd = SCMD_MODE_SENSE;
20370 		cdb.cdb_opaque[2] = page_code;
20371 		FORMG0COUNT(&cdb, buflen);
20372 	} else {
20373 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
20374 		cdb.cdb_opaque[2] = page_code;
20375 		FORMG1COUNT(&cdb, buflen);
20376 	}
20377 
20378 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
20379 
20380 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20381 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
20382 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20383 	ucmd_buf.uscsi_buflen	= buflen;
20384 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20385 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20386 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20387 	ucmd_buf.uscsi_timeout	= 60;
20388 
20389 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
20390 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
20391 
20392 	switch (status) {
20393 	case 0:
20394 		break;	/* Success! */
20395 	case EIO:
20396 		switch (ucmd_buf.uscsi_status) {
20397 		case STATUS_RESERVATION_CONFLICT:
20398 			status = EACCES;
20399 			break;
20400 		default:
20401 			break;
20402 		}
20403 		break;
20404 	default:
20405 		break;
20406 	}
20407 
20408 	if (status == 0) {
20409 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
20410 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20411 	}
20412 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
20413 
20414 	return (status);
20415 }
20416 
20417 
20418 /*
20419  *    Function: sd_send_scsi_MODE_SELECT
20420  *
20421  * Description: Utility function for issuing a scsi MODE SELECT command.
20422  *		Note: This routine uses a consistent implementation for Group0,
20423  *		Group1, and Group2 commands across all platforms. ATAPI devices
20424  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
20425  *
20426  *   Arguments: un - pointer to the softstate struct for the target.
20427  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
20428  *			  CDB_GROUP[1|2] (10 byte).
20429  *		bufaddr - buffer for page data retrieved from the target.
20430  *		buflen - size of page to be retrieved.
20431  *		save_page - boolean to determin if SP bit should be set.
20432  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20433  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20434  *			to use the USCSI "direct" chain and bypass the normal
20435  *			command waitq.
20436  *
20437  * Return Code: 0   - Success
20438  *		errno return code from sd_send_scsi_cmd()
20439  *
20440  *     Context: Can sleep. Does not return until command is completed.
20441  */
20442 
20443 static int
20444 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
20445 	size_t buflen,  uchar_t save_page, int path_flag)
20446 {
20447 	struct	scsi_extended_sense	sense_buf;
20448 	union scsi_cdb		cdb;
20449 	struct uscsi_cmd	ucmd_buf;
20450 	int			status;
20451 
20452 	ASSERT(un != NULL);
20453 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20454 	ASSERT(bufaddr != NULL);
20455 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
20456 	    (cdbsize == CDB_GROUP2));
20457 
20458 	SD_TRACE(SD_LOG_IO, un,
20459 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
20460 
20461 	bzero(&cdb, sizeof (cdb));
20462 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20463 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20464 
20465 	/* Set the PF bit for many third party drives */
20466 	cdb.cdb_opaque[1] = 0x10;
20467 
20468 	/* Set the savepage(SP) bit if given */
20469 	if (save_page == SD_SAVE_PAGE) {
20470 		cdb.cdb_opaque[1] |= 0x01;
20471 	}
20472 
20473 	if (cdbsize == CDB_GROUP0) {
20474 		cdb.scc_cmd = SCMD_MODE_SELECT;
20475 		FORMG0COUNT(&cdb, buflen);
20476 	} else {
20477 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
20478 		FORMG1COUNT(&cdb, buflen);
20479 	}
20480 
20481 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
20482 
20483 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20484 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
20485 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20486 	ucmd_buf.uscsi_buflen	= buflen;
20487 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20488 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20489 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20490 	ucmd_buf.uscsi_timeout	= 60;
20491 
20492 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
20493 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
20494 
20495 	switch (status) {
20496 	case 0:
20497 		break;	/* Success! */
20498 	case EIO:
20499 		switch (ucmd_buf.uscsi_status) {
20500 		case STATUS_RESERVATION_CONFLICT:
20501 			status = EACCES;
20502 			break;
20503 		default:
20504 			break;
20505 		}
20506 		break;
20507 	default:
20508 		break;
20509 	}
20510 
20511 	if (status == 0) {
20512 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
20513 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20514 	}
20515 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
20516 
20517 	return (status);
20518 }
20519 
20520 
20521 /*
20522  *    Function: sd_send_scsi_RDWR
20523  *
20524  * Description: Issue a scsi READ or WRITE command with the given parameters.
20525  *
20526  *   Arguments: un:      Pointer to the sd_lun struct for the target.
20527  *		cmd:	 SCMD_READ or SCMD_WRITE
20528  *		bufaddr: Address of caller's buffer to receive the RDWR data
20529  *		buflen:  Length of caller's buffer receive the RDWR data.
20530  *		start_block: Block number for the start of the RDWR operation.
20531  *			 (Assumes target-native block size.)
20532  *		residp:  Pointer to variable to receive the redisual of the
20533  *			 RDWR operation (may be NULL of no residual requested).
20534  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20535  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20536  *			to use the USCSI "direct" chain and bypass the normal
20537  *			command waitq.
20538  *
20539  * Return Code: 0   - Success
20540  *		errno return code from sd_send_scsi_cmd()
20541  *
20542  *     Context: Can sleep. Does not return until command is completed.
20543  */
20544 
20545 static int
20546 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
20547 	size_t buflen, daddr_t start_block, int path_flag)
20548 {
20549 	struct	scsi_extended_sense	sense_buf;
20550 	union scsi_cdb		cdb;
20551 	struct uscsi_cmd	ucmd_buf;
20552 	uint32_t		block_count;
20553 	int			status;
20554 	int			cdbsize;
20555 	uchar_t			flag;
20556 
20557 	ASSERT(un != NULL);
20558 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20559 	ASSERT(bufaddr != NULL);
20560 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
20561 
20562 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
20563 
20564 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
20565 		return (EINVAL);
20566 	}
20567 
20568 	mutex_enter(SD_MUTEX(un));
20569 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
20570 	mutex_exit(SD_MUTEX(un));
20571 
20572 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
20573 
20574 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
20575 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
20576 	    bufaddr, buflen, start_block, block_count);
20577 
20578 	bzero(&cdb, sizeof (cdb));
20579 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20580 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20581 
20582 	/* Compute CDB size to use */
20583 	if (start_block > 0xffffffff)
20584 		cdbsize = CDB_GROUP4;
20585 	else if ((start_block & 0xFFE00000) ||
20586 	    (un->un_f_cfg_is_atapi == TRUE))
20587 		cdbsize = CDB_GROUP1;
20588 	else
20589 		cdbsize = CDB_GROUP0;
20590 
20591 	switch (cdbsize) {
20592 	case CDB_GROUP0:	/* 6-byte CDBs */
20593 		cdb.scc_cmd = cmd;
20594 		FORMG0ADDR(&cdb, start_block);
20595 		FORMG0COUNT(&cdb, block_count);
20596 		break;
20597 	case CDB_GROUP1:	/* 10-byte CDBs */
20598 		cdb.scc_cmd = cmd | SCMD_GROUP1;
20599 		FORMG1ADDR(&cdb, start_block);
20600 		FORMG1COUNT(&cdb, block_count);
20601 		break;
20602 	case CDB_GROUP4:	/* 16-byte CDBs */
20603 		cdb.scc_cmd = cmd | SCMD_GROUP4;
20604 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
20605 		FORMG4COUNT(&cdb, block_count);
20606 		break;
20607 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
20608 	default:
20609 		/* All others reserved */
20610 		return (EINVAL);
20611 	}
20612 
20613 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
20614 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
20615 
20616 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20617 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
20618 	ucmd_buf.uscsi_bufaddr	= bufaddr;
20619 	ucmd_buf.uscsi_buflen	= buflen;
20620 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20621 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20622 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
20623 	ucmd_buf.uscsi_timeout	= 60;
20624 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
20625 				UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
20626 	switch (status) {
20627 	case 0:
20628 		break;	/* Success! */
20629 	case EIO:
20630 		switch (ucmd_buf.uscsi_status) {
20631 		case STATUS_RESERVATION_CONFLICT:
20632 			status = EACCES;
20633 			break;
20634 		default:
20635 			break;
20636 		}
20637 		break;
20638 	default:
20639 		break;
20640 	}
20641 
20642 	if (status == 0) {
20643 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
20644 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20645 	}
20646 
20647 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
20648 
20649 	return (status);
20650 }
20651 
20652 
20653 /*
20654  *    Function: sd_send_scsi_LOG_SENSE
20655  *
20656  * Description: Issue a scsi LOG_SENSE command with the given parameters.
20657  *
20658  *   Arguments: un:      Pointer to the sd_lun struct for the target.
20659  *
20660  * Return Code: 0   - Success
20661  *		errno return code from sd_send_scsi_cmd()
20662  *
20663  *     Context: Can sleep. Does not return until command is completed.
20664  */
20665 
20666 static int
20667 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
20668 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
20669 	int path_flag)
20670 
20671 {
20672 	struct	scsi_extended_sense	sense_buf;
20673 	union scsi_cdb		cdb;
20674 	struct uscsi_cmd	ucmd_buf;
20675 	int			status;
20676 
20677 	ASSERT(un != NULL);
20678 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20679 
20680 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
20681 
20682 	bzero(&cdb, sizeof (cdb));
20683 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20684 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20685 
20686 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
20687 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
20688 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
20689 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
20690 	FORMG1COUNT(&cdb, buflen);
20691 
20692 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20693 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20694 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20695 	ucmd_buf.uscsi_buflen	= buflen;
20696 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20697 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20698 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20699 	ucmd_buf.uscsi_timeout	= 60;
20700 
20701 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, UIO_SYSSPACE,
20702 	    UIO_SYSSPACE, UIO_SYSSPACE, path_flag);
20703 
20704 	switch (status) {
20705 	case 0:
20706 		break;
20707 	case EIO:
20708 		switch (ucmd_buf.uscsi_status) {
20709 		case STATUS_RESERVATION_CONFLICT:
20710 			status = EACCES;
20711 			break;
20712 		case STATUS_CHECK:
20713 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20714 			    (sense_buf.es_key == KEY_ILLEGAL_REQUEST) &&
20715 			    (sense_buf.es_add_code == 0x24)) {
20716 				/*
20717 				 * ASC 0x24: INVALID FIELD IN CDB
20718 				 */
20719 				switch (page_code) {
20720 				case START_STOP_CYCLE_PAGE:
20721 					/*
20722 					 * The start stop cycle counter is
20723 					 * implemented as page 0x31 in earlier
20724 					 * generation disks. In new generation
20725 					 * disks the start stop cycle counter is
20726 					 * implemented as page 0xE. To properly
20727 					 * handle this case if an attempt for
20728 					 * log page 0xE is made and fails we
20729 					 * will try again using page 0x31.
20730 					 *
20731 					 * Network storage BU committed to
20732 					 * maintain the page 0x31 for this
20733 					 * purpose and will not have any other
20734 					 * page implemented with page code 0x31
20735 					 * until all disks transition to the
20736 					 * standard page.
20737 					 */
20738 					mutex_enter(SD_MUTEX(un));
20739 					un->un_start_stop_cycle_page =
20740 					    START_STOP_CYCLE_VU_PAGE;
20741 					cdb.cdb_opaque[2] =
20742 					    (char)(page_control << 6) |
20743 					    un->un_start_stop_cycle_page;
20744 					mutex_exit(SD_MUTEX(un));
20745 					status = sd_send_scsi_cmd(
20746 					    SD_GET_DEV(un), &ucmd_buf,
20747 					    UIO_SYSSPACE, UIO_SYSSPACE,
20748 					    UIO_SYSSPACE, path_flag);
20749 
20750 					break;
20751 				case TEMPERATURE_PAGE:
20752 					status = ENOTTY;
20753 					break;
20754 				default:
20755 					break;
20756 				}
20757 			}
20758 			break;
20759 		default:
20760 			break;
20761 		}
20762 		break;
20763 	default:
20764 		break;
20765 	}
20766 
20767 	if (status == 0) {
20768 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
20769 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20770 	}
20771 
20772 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
20773 
20774 	return (status);
20775 }
20776 
20777 
20778 /*
20779  *    Function: sdioctl
20780  *
20781  * Description: Driver's ioctl(9e) entry point function.
20782  *
20783  *   Arguments: dev     - device number
20784  *		cmd     - ioctl operation to be performed
20785  *		arg     - user argument, contains data to be set or reference
20786  *			  parameter for get
20787  *		flag    - bit flag, indicating open settings, 32/64 bit type
20788  *		cred_p  - user credential pointer
20789  *		rval_p  - calling process return value (OPT)
20790  *
20791  * Return Code: EINVAL
20792  *		ENOTTY
20793  *		ENXIO
20794  *		EIO
20795  *		EFAULT
20796  *		ENOTSUP
20797  *		EPERM
20798  *
20799  *     Context: Called from the device switch at normal priority.
20800  */
20801 
20802 static int
20803 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
20804 {
20805 	struct sd_lun	*un = NULL;
20806 	int		geom_validated = FALSE;
20807 	int		err = 0;
20808 	int		i = 0;
20809 	cred_t		*cr;
20810 
20811 	/*
20812 	 * All device accesses go thru sdstrategy where we check on suspend
20813 	 * status
20814 	 */
20815 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20816 		return (ENXIO);
20817 	}
20818 
20819 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20820 
20821 	/*
20822 	 * Moved this wait from sd_uscsi_strategy to here for
20823 	 * reasons of deadlock prevention. Internal driver commands,
20824 	 * specifically those to change a devices power level, result
20825 	 * in a call to sd_uscsi_strategy.
20826 	 */
20827 	mutex_enter(SD_MUTEX(un));
20828 	while ((un->un_state == SD_STATE_SUSPENDED) ||
20829 	    (un->un_state == SD_STATE_PM_CHANGING)) {
20830 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
20831 	}
20832 	/*
20833 	 * Twiddling the counter here protects commands from now
20834 	 * through to the top of sd_uscsi_strategy. Without the
20835 	 * counter inc. a power down, for example, could get in
20836 	 * after the above check for state is made and before
20837 	 * execution gets to the top of sd_uscsi_strategy.
20838 	 * That would cause problems.
20839 	 */
20840 	un->un_ncmds_in_driver++;
20841 
20842 	if ((un->un_f_geometry_is_valid == FALSE) &&
20843 	    (flag & (FNDELAY | FNONBLOCK))) {
20844 		switch (cmd) {
20845 		case CDROMPAUSE:
20846 		case CDROMRESUME:
20847 		case CDROMPLAYMSF:
20848 		case CDROMPLAYTRKIND:
20849 		case CDROMREADTOCHDR:
20850 		case CDROMREADTOCENTRY:
20851 		case CDROMSTOP:
20852 		case CDROMSTART:
20853 		case CDROMVOLCTRL:
20854 		case CDROMSUBCHNL:
20855 		case CDROMREADMODE2:
20856 		case CDROMREADMODE1:
20857 		case CDROMREADOFFSET:
20858 		case CDROMSBLKMODE:
20859 		case CDROMGBLKMODE:
20860 		case CDROMGDRVSPEED:
20861 		case CDROMSDRVSPEED:
20862 		case CDROMCDDA:
20863 		case CDROMCDXA:
20864 		case CDROMSUBCODE:
20865 			if (!ISCD(un)) {
20866 				un->un_ncmds_in_driver--;
20867 				ASSERT(un->un_ncmds_in_driver >= 0);
20868 				mutex_exit(SD_MUTEX(un));
20869 				return (ENOTTY);
20870 			}
20871 			break;
20872 		case FDEJECT:
20873 		case DKIOCEJECT:
20874 		case CDROMEJECT:
20875 			if (!un->un_f_eject_media_supported) {
20876 				un->un_ncmds_in_driver--;
20877 				ASSERT(un->un_ncmds_in_driver >= 0);
20878 				mutex_exit(SD_MUTEX(un));
20879 				return (ENOTTY);
20880 			}
20881 			break;
20882 		case DKIOCSVTOC:
20883 		case DKIOCSETEFI:
20884 		case DKIOCSMBOOT:
20885 		case DKIOCFLUSHWRITECACHE:
20886 			mutex_exit(SD_MUTEX(un));
20887 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
20888 			if (err != 0) {
20889 				mutex_enter(SD_MUTEX(un));
20890 				un->un_ncmds_in_driver--;
20891 				ASSERT(un->un_ncmds_in_driver >= 0);
20892 				mutex_exit(SD_MUTEX(un));
20893 				return (EIO);
20894 			}
20895 			mutex_enter(SD_MUTEX(un));
20896 			/* FALLTHROUGH */
20897 		case DKIOCREMOVABLE:
20898 		case DKIOCHOTPLUGGABLE:
20899 		case DKIOCINFO:
20900 		case DKIOCGMEDIAINFO:
20901 		case MHIOCENFAILFAST:
20902 		case MHIOCSTATUS:
20903 		case MHIOCTKOWN:
20904 		case MHIOCRELEASE:
20905 		case MHIOCGRP_INKEYS:
20906 		case MHIOCGRP_INRESV:
20907 		case MHIOCGRP_REGISTER:
20908 		case MHIOCGRP_RESERVE:
20909 		case MHIOCGRP_PREEMPTANDABORT:
20910 		case MHIOCGRP_REGISTERANDIGNOREKEY:
20911 		case CDROMCLOSETRAY:
20912 		case USCSICMD:
20913 			goto skip_ready_valid;
20914 		default:
20915 			break;
20916 		}
20917 
20918 		mutex_exit(SD_MUTEX(un));
20919 		err = sd_ready_and_valid(un);
20920 		mutex_enter(SD_MUTEX(un));
20921 		if (err == SD_READY_NOT_VALID) {
20922 			switch (cmd) {
20923 			case DKIOCGAPART:
20924 			case DKIOCGGEOM:
20925 			case DKIOCSGEOM:
20926 			case DKIOCGVTOC:
20927 			case DKIOCSVTOC:
20928 			case DKIOCSAPART:
20929 			case DKIOCG_PHYGEOM:
20930 			case DKIOCG_VIRTGEOM:
20931 				err = ENOTSUP;
20932 				un->un_ncmds_in_driver--;
20933 				ASSERT(un->un_ncmds_in_driver >= 0);
20934 				mutex_exit(SD_MUTEX(un));
20935 				return (err);
20936 			}
20937 		}
20938 		if (err != SD_READY_VALID) {
20939 			switch (cmd) {
20940 			case DKIOCSTATE:
20941 			case CDROMGDRVSPEED:
20942 			case CDROMSDRVSPEED:
20943 			case FDEJECT:	/* for eject command */
20944 			case DKIOCEJECT:
20945 			case CDROMEJECT:
20946 			case DKIOCGETEFI:
20947 			case DKIOCSGEOM:
20948 			case DKIOCREMOVABLE:
20949 			case DKIOCHOTPLUGGABLE:
20950 			case DKIOCSAPART:
20951 			case DKIOCSETEFI:
20952 				break;
20953 			default:
20954 				if (un->un_f_has_removable_media) {
20955 					err = ENXIO;
20956 				} else {
20957 					/* Do not map EACCES to EIO */
20958 					if (err != EACCES)
20959 						err = EIO;
20960 				}
20961 				un->un_ncmds_in_driver--;
20962 				ASSERT(un->un_ncmds_in_driver >= 0);
20963 				mutex_exit(SD_MUTEX(un));
20964 				return (err);
20965 			}
20966 		}
20967 		geom_validated = TRUE;
20968 	}
20969 	if ((un->un_f_geometry_is_valid == TRUE) &&
20970 	    (un->un_solaris_size > 0)) {
20971 		/*
20972 		 * the "geometry_is_valid" flag could be true if we
20973 		 * have an fdisk table but no Solaris partition
20974 		 */
20975 		if (un->un_vtoc.v_sanity != VTOC_SANE) {
20976 			/* it is EFI, so return ENOTSUP for these */
20977 			switch (cmd) {
20978 			case DKIOCGAPART:
20979 			case DKIOCGGEOM:
20980 			case DKIOCGVTOC:
20981 			case DKIOCSVTOC:
20982 			case DKIOCSAPART:
20983 				err = ENOTSUP;
20984 				un->un_ncmds_in_driver--;
20985 				ASSERT(un->un_ncmds_in_driver >= 0);
20986 				mutex_exit(SD_MUTEX(un));
20987 				return (err);
20988 			}
20989 		}
20990 	}
20991 
20992 skip_ready_valid:
20993 	mutex_exit(SD_MUTEX(un));
20994 
20995 	switch (cmd) {
20996 	case DKIOCINFO:
20997 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
20998 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
20999 		break;
21000 
21001 	case DKIOCGMEDIAINFO:
21002 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
21003 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
21004 		break;
21005 
21006 	case DKIOCGGEOM:
21007 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGGEOM\n");
21008 		err = sd_dkio_get_geometry(dev, (caddr_t)arg, flag,
21009 		    geom_validated);
21010 		break;
21011 
21012 	case DKIOCSGEOM:
21013 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSGEOM\n");
21014 		err = sd_dkio_set_geometry(dev, (caddr_t)arg, flag);
21015 		break;
21016 
21017 	case DKIOCGAPART:
21018 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGAPART\n");
21019 		err = sd_dkio_get_partition(dev, (caddr_t)arg, flag,
21020 		    geom_validated);
21021 		break;
21022 
21023 	case DKIOCSAPART:
21024 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSAPART\n");
21025 		err = sd_dkio_set_partition(dev, (caddr_t)arg, flag);
21026 		break;
21027 
21028 	case DKIOCGVTOC:
21029 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGVTOC\n");
21030 		err = sd_dkio_get_vtoc(dev, (caddr_t)arg, flag,
21031 		    geom_validated);
21032 		break;
21033 
21034 	case DKIOCGETEFI:
21035 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGETEFI\n");
21036 		err = sd_dkio_get_efi(dev, (caddr_t)arg, flag);
21037 		break;
21038 
21039 	case DKIOCPARTITION:
21040 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCPARTITION\n");
21041 		err = sd_dkio_partition(dev, (caddr_t)arg, flag);
21042 		break;
21043 
21044 	case DKIOCSVTOC:
21045 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSVTOC\n");
21046 		err = sd_dkio_set_vtoc(dev, (caddr_t)arg, flag);
21047 		break;
21048 
21049 	case DKIOCSETEFI:
21050 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSETEFI\n");
21051 		err = sd_dkio_set_efi(dev, (caddr_t)arg, flag);
21052 		break;
21053 
21054 	case DKIOCGMBOOT:
21055 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMBOOT\n");
21056 		err = sd_dkio_get_mboot(dev, (caddr_t)arg, flag);
21057 		break;
21058 
21059 	case DKIOCSMBOOT:
21060 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSMBOOT\n");
21061 		err = sd_dkio_set_mboot(dev, (caddr_t)arg, flag);
21062 		break;
21063 
21064 	case DKIOCLOCK:
21065 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
21066 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
21067 		    SD_PATH_STANDARD);
21068 		break;
21069 
21070 	case DKIOCUNLOCK:
21071 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
21072 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
21073 		    SD_PATH_STANDARD);
21074 		break;
21075 
21076 	case DKIOCSTATE: {
21077 		enum dkio_state		state;
21078 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
21079 
21080 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
21081 			err = EFAULT;
21082 		} else {
21083 			err = sd_check_media(dev, state);
21084 			if (err == 0) {
21085 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
21086 				    sizeof (int), flag) != 0)
21087 					err = EFAULT;
21088 			}
21089 		}
21090 		break;
21091 	}
21092 
21093 	case DKIOCREMOVABLE:
21094 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
21095 		/*
21096 		 * At present, vold only does automount for removable-media
21097 		 * devices, in order not to break current applications, we
21098 		 * still let hopluggable devices pretend to be removable media
21099 		 * devices for vold. In the near future, once vold is EOL'ed,
21100 		 * we should remove this workaround.
21101 		 */
21102 		if (un->un_f_has_removable_media || un->un_f_is_hotpluggable) {
21103 			i = 1;
21104 		} else {
21105 			i = 0;
21106 		}
21107 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21108 			err = EFAULT;
21109 		} else {
21110 			err = 0;
21111 		}
21112 		break;
21113 
21114 	case DKIOCHOTPLUGGABLE:
21115 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
21116 		if (un->un_f_is_hotpluggable) {
21117 			i = 1;
21118 		} else {
21119 			i = 0;
21120 		}
21121 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21122 			err = EFAULT;
21123 		} else {
21124 			err = 0;
21125 		}
21126 		break;
21127 
21128 	case DKIOCGTEMPERATURE:
21129 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
21130 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
21131 		break;
21132 
21133 	case MHIOCENFAILFAST:
21134 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
21135 		if ((err = drv_priv(cred_p)) == 0) {
21136 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
21137 		}
21138 		break;
21139 
21140 	case MHIOCTKOWN:
21141 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
21142 		if ((err = drv_priv(cred_p)) == 0) {
21143 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
21144 		}
21145 		break;
21146 
21147 	case MHIOCRELEASE:
21148 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
21149 		if ((err = drv_priv(cred_p)) == 0) {
21150 			err = sd_mhdioc_release(dev);
21151 		}
21152 		break;
21153 
21154 	case MHIOCSTATUS:
21155 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
21156 		if ((err = drv_priv(cred_p)) == 0) {
21157 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
21158 			case 0:
21159 				err = 0;
21160 				break;
21161 			case EACCES:
21162 				*rval_p = 1;
21163 				err = 0;
21164 				break;
21165 			default:
21166 				err = EIO;
21167 				break;
21168 			}
21169 		}
21170 		break;
21171 
21172 	case MHIOCQRESERVE:
21173 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
21174 		if ((err = drv_priv(cred_p)) == 0) {
21175 			err = sd_reserve_release(dev, SD_RESERVE);
21176 		}
21177 		break;
21178 
21179 	case MHIOCREREGISTERDEVID:
21180 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
21181 		if (drv_priv(cred_p) == EPERM) {
21182 			err = EPERM;
21183 		} else if (!un->un_f_devid_supported) {
21184 			err = ENOTTY;
21185 		} else {
21186 			err = sd_mhdioc_register_devid(dev);
21187 		}
21188 		break;
21189 
21190 	case MHIOCGRP_INKEYS:
21191 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
21192 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21193 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21194 				err = ENOTSUP;
21195 			} else {
21196 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
21197 				    flag);
21198 			}
21199 		}
21200 		break;
21201 
21202 	case MHIOCGRP_INRESV:
21203 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
21204 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21205 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21206 				err = ENOTSUP;
21207 			} else {
21208 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
21209 			}
21210 		}
21211 		break;
21212 
21213 	case MHIOCGRP_REGISTER:
21214 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
21215 		if ((err = drv_priv(cred_p)) != EPERM) {
21216 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21217 				err = ENOTSUP;
21218 			} else if (arg != NULL) {
21219 				mhioc_register_t reg;
21220 				if (ddi_copyin((void *)arg, &reg,
21221 				    sizeof (mhioc_register_t), flag) != 0) {
21222 					err = EFAULT;
21223 				} else {
21224 					err =
21225 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21226 					    un, SD_SCSI3_REGISTER,
21227 					    (uchar_t *)&reg);
21228 				}
21229 			}
21230 		}
21231 		break;
21232 
21233 	case MHIOCGRP_RESERVE:
21234 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
21235 		if ((err = drv_priv(cred_p)) != EPERM) {
21236 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21237 				err = ENOTSUP;
21238 			} else if (arg != NULL) {
21239 				mhioc_resv_desc_t resv_desc;
21240 				if (ddi_copyin((void *)arg, &resv_desc,
21241 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
21242 					err = EFAULT;
21243 				} else {
21244 					err =
21245 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21246 					    un, SD_SCSI3_RESERVE,
21247 					    (uchar_t *)&resv_desc);
21248 				}
21249 			}
21250 		}
21251 		break;
21252 
21253 	case MHIOCGRP_PREEMPTANDABORT:
21254 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
21255 		if ((err = drv_priv(cred_p)) != EPERM) {
21256 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21257 				err = ENOTSUP;
21258 			} else if (arg != NULL) {
21259 				mhioc_preemptandabort_t preempt_abort;
21260 				if (ddi_copyin((void *)arg, &preempt_abort,
21261 				    sizeof (mhioc_preemptandabort_t),
21262 				    flag) != 0) {
21263 					err = EFAULT;
21264 				} else {
21265 					err =
21266 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21267 					    un, SD_SCSI3_PREEMPTANDABORT,
21268 					    (uchar_t *)&preempt_abort);
21269 				}
21270 			}
21271 		}
21272 		break;
21273 
21274 	case MHIOCGRP_REGISTERANDIGNOREKEY:
21275 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
21276 		if ((err = drv_priv(cred_p)) != EPERM) {
21277 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21278 				err = ENOTSUP;
21279 			} else if (arg != NULL) {
21280 				mhioc_registerandignorekey_t r_and_i;
21281 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
21282 				    sizeof (mhioc_registerandignorekey_t),
21283 				    flag) != 0) {
21284 					err = EFAULT;
21285 				} else {
21286 					err =
21287 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21288 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
21289 					    (uchar_t *)&r_and_i);
21290 				}
21291 			}
21292 		}
21293 		break;
21294 
21295 	case USCSICMD:
21296 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
21297 		cr = ddi_get_cred();
21298 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
21299 			err = EPERM;
21300 		} else {
21301 			err = sd_uscsi_ioctl(dev, (caddr_t)arg, flag);
21302 		}
21303 		break;
21304 
21305 	case CDROMPAUSE:
21306 	case CDROMRESUME:
21307 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
21308 		if (!ISCD(un)) {
21309 			err = ENOTTY;
21310 		} else {
21311 			err = sr_pause_resume(dev, cmd);
21312 		}
21313 		break;
21314 
21315 	case CDROMPLAYMSF:
21316 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
21317 		if (!ISCD(un)) {
21318 			err = ENOTTY;
21319 		} else {
21320 			err = sr_play_msf(dev, (caddr_t)arg, flag);
21321 		}
21322 		break;
21323 
21324 	case CDROMPLAYTRKIND:
21325 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
21326 #if defined(__i386) || defined(__amd64)
21327 		/*
21328 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
21329 		 */
21330 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21331 #else
21332 		if (!ISCD(un)) {
21333 #endif
21334 			err = ENOTTY;
21335 		} else {
21336 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
21337 		}
21338 		break;
21339 
21340 	case CDROMREADTOCHDR:
21341 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
21342 		if (!ISCD(un)) {
21343 			err = ENOTTY;
21344 		} else {
21345 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
21346 		}
21347 		break;
21348 
21349 	case CDROMREADTOCENTRY:
21350 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
21351 		if (!ISCD(un)) {
21352 			err = ENOTTY;
21353 		} else {
21354 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
21355 		}
21356 		break;
21357 
21358 	case CDROMSTOP:
21359 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
21360 		if (!ISCD(un)) {
21361 			err = ENOTTY;
21362 		} else {
21363 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
21364 			    SD_PATH_STANDARD);
21365 		}
21366 		break;
21367 
21368 	case CDROMSTART:
21369 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
21370 		if (!ISCD(un)) {
21371 			err = ENOTTY;
21372 		} else {
21373 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
21374 			    SD_PATH_STANDARD);
21375 		}
21376 		break;
21377 
21378 	case CDROMCLOSETRAY:
21379 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
21380 		if (!ISCD(un)) {
21381 			err = ENOTTY;
21382 		} else {
21383 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
21384 			    SD_PATH_STANDARD);
21385 		}
21386 		break;
21387 
21388 	case FDEJECT:	/* for eject command */
21389 	case DKIOCEJECT:
21390 	case CDROMEJECT:
21391 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
21392 		if (!un->un_f_eject_media_supported) {
21393 			err = ENOTTY;
21394 		} else {
21395 			err = sr_eject(dev);
21396 		}
21397 		break;
21398 
21399 	case CDROMVOLCTRL:
21400 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
21401 		if (!ISCD(un)) {
21402 			err = ENOTTY;
21403 		} else {
21404 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
21405 		}
21406 		break;
21407 
21408 	case CDROMSUBCHNL:
21409 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
21410 		if (!ISCD(un)) {
21411 			err = ENOTTY;
21412 		} else {
21413 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
21414 		}
21415 		break;
21416 
21417 	case CDROMREADMODE2:
21418 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
21419 		if (!ISCD(un)) {
21420 			err = ENOTTY;
21421 		} else if (un->un_f_cfg_is_atapi == TRUE) {
21422 			/*
21423 			 * If the drive supports READ CD, use that instead of
21424 			 * switching the LBA size via a MODE SELECT
21425 			 * Block Descriptor
21426 			 */
21427 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
21428 		} else {
21429 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
21430 		}
21431 		break;
21432 
21433 	case CDROMREADMODE1:
21434 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
21435 		if (!ISCD(un)) {
21436 			err = ENOTTY;
21437 		} else {
21438 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
21439 		}
21440 		break;
21441 
21442 	case CDROMREADOFFSET:
21443 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
21444 		if (!ISCD(un)) {
21445 			err = ENOTTY;
21446 		} else {
21447 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
21448 			    flag);
21449 		}
21450 		break;
21451 
21452 	case CDROMSBLKMODE:
21453 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
21454 		/*
21455 		 * There is no means of changing block size in case of atapi
21456 		 * drives, thus return ENOTTY if drive type is atapi
21457 		 */
21458 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21459 			err = ENOTTY;
21460 		} else if (un->un_f_mmc_cap == TRUE) {
21461 
21462 			/*
21463 			 * MMC Devices do not support changing the
21464 			 * logical block size
21465 			 *
21466 			 * Note: EINVAL is being returned instead of ENOTTY to
21467 			 * maintain consistancy with the original mmc
21468 			 * driver update.
21469 			 */
21470 			err = EINVAL;
21471 		} else {
21472 			mutex_enter(SD_MUTEX(un));
21473 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
21474 			    (un->un_ncmds_in_transport > 0)) {
21475 				mutex_exit(SD_MUTEX(un));
21476 				err = EINVAL;
21477 			} else {
21478 				mutex_exit(SD_MUTEX(un));
21479 				err = sr_change_blkmode(dev, cmd, arg, flag);
21480 			}
21481 		}
21482 		break;
21483 
21484 	case CDROMGBLKMODE:
21485 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
21486 		if (!ISCD(un)) {
21487 			err = ENOTTY;
21488 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
21489 		    (un->un_f_blockcount_is_valid != FALSE)) {
21490 			/*
21491 			 * Drive is an ATAPI drive so return target block
21492 			 * size for ATAPI drives since we cannot change the
21493 			 * blocksize on ATAPI drives. Used primarily to detect
21494 			 * if an ATAPI cdrom is present.
21495 			 */
21496 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
21497 			    sizeof (int), flag) != 0) {
21498 				err = EFAULT;
21499 			} else {
21500 				err = 0;
21501 			}
21502 
21503 		} else {
21504 			/*
21505 			 * Drive supports changing block sizes via a Mode
21506 			 * Select.
21507 			 */
21508 			err = sr_change_blkmode(dev, cmd, arg, flag);
21509 		}
21510 		break;
21511 
21512 	case CDROMGDRVSPEED:
21513 	case CDROMSDRVSPEED:
21514 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
21515 		if (!ISCD(un)) {
21516 			err = ENOTTY;
21517 		} else if (un->un_f_mmc_cap == TRUE) {
21518 			/*
21519 			 * Note: In the future the driver implementation
21520 			 * for getting and
21521 			 * setting cd speed should entail:
21522 			 * 1) If non-mmc try the Toshiba mode page
21523 			 *    (sr_change_speed)
21524 			 * 2) If mmc but no support for Real Time Streaming try
21525 			 *    the SET CD SPEED (0xBB) command
21526 			 *   (sr_atapi_change_speed)
21527 			 * 3) If mmc and support for Real Time Streaming
21528 			 *    try the GET PERFORMANCE and SET STREAMING
21529 			 *    commands (not yet implemented, 4380808)
21530 			 */
21531 			/*
21532 			 * As per recent MMC spec, CD-ROM speed is variable
21533 			 * and changes with LBA. Since there is no such
21534 			 * things as drive speed now, fail this ioctl.
21535 			 *
21536 			 * Note: EINVAL is returned for consistancy of original
21537 			 * implementation which included support for getting
21538 			 * the drive speed of mmc devices but not setting
21539 			 * the drive speed. Thus EINVAL would be returned
21540 			 * if a set request was made for an mmc device.
21541 			 * We no longer support get or set speed for
21542 			 * mmc but need to remain consistant with regard
21543 			 * to the error code returned.
21544 			 */
21545 			err = EINVAL;
21546 		} else if (un->un_f_cfg_is_atapi == TRUE) {
21547 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
21548 		} else {
21549 			err = sr_change_speed(dev, cmd, arg, flag);
21550 		}
21551 		break;
21552 
21553 	case CDROMCDDA:
21554 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
21555 		if (!ISCD(un)) {
21556 			err = ENOTTY;
21557 		} else {
21558 			err = sr_read_cdda(dev, (void *)arg, flag);
21559 		}
21560 		break;
21561 
21562 	case CDROMCDXA:
21563 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
21564 		if (!ISCD(un)) {
21565 			err = ENOTTY;
21566 		} else {
21567 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
21568 		}
21569 		break;
21570 
21571 	case CDROMSUBCODE:
21572 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
21573 		if (!ISCD(un)) {
21574 			err = ENOTTY;
21575 		} else {
21576 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
21577 		}
21578 		break;
21579 
21580 	case DKIOCPARTINFO: {
21581 		/*
21582 		 * Return parameters describing the selected disk slice.
21583 		 * Note: this ioctl is for the intel platform only
21584 		 */
21585 #if defined(__i386) || defined(__amd64)
21586 		int part;
21587 
21588 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCPARTINFO\n");
21589 		part = SDPART(dev);
21590 
21591 		/* don't check un_solaris_size for pN */
21592 		if (part < P0_RAW_DISK && un->un_solaris_size == 0) {
21593 			err = EIO;
21594 		} else {
21595 			struct part_info p;
21596 
21597 			p.p_start = (daddr_t)un->un_offset[part];
21598 			p.p_length = (int)un->un_map[part].dkl_nblk;
21599 #ifdef _MULTI_DATAMODEL
21600 			switch (ddi_model_convert_from(flag & FMODELS)) {
21601 			case DDI_MODEL_ILP32:
21602 			{
21603 				struct part_info32 p32;
21604 
21605 				p32.p_start = (daddr32_t)p.p_start;
21606 				p32.p_length = p.p_length;
21607 				if (ddi_copyout(&p32, (void *)arg,
21608 				    sizeof (p32), flag))
21609 					err = EFAULT;
21610 				break;
21611 			}
21612 
21613 			case DDI_MODEL_NONE:
21614 			{
21615 				if (ddi_copyout(&p, (void *)arg, sizeof (p),
21616 				    flag))
21617 					err = EFAULT;
21618 				break;
21619 			}
21620 			}
21621 #else /* ! _MULTI_DATAMODEL */
21622 			if (ddi_copyout(&p, (void *)arg, sizeof (p), flag))
21623 				err = EFAULT;
21624 #endif /* _MULTI_DATAMODEL */
21625 		}
21626 #else
21627 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCPARTINFO\n");
21628 		err = ENOTTY;
21629 #endif
21630 		break;
21631 	}
21632 
21633 	case DKIOCG_PHYGEOM: {
21634 		/* Return the driver's notion of the media physical geometry */
21635 #if defined(__i386) || defined(__amd64)
21636 		struct dk_geom	disk_geom;
21637 		struct dk_geom	*dkgp = &disk_geom;
21638 
21639 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCG_PHYGEOM\n");
21640 		mutex_enter(SD_MUTEX(un));
21641 
21642 		if (un->un_g.dkg_nhead != 0 &&
21643 		    un->un_g.dkg_nsect != 0) {
21644 			/*
21645 			 * We succeeded in getting a geometry, but
21646 			 * right now it is being reported as just the
21647 			 * Solaris fdisk partition, just like for
21648 			 * DKIOCGGEOM. We need to change that to be
21649 			 * correct for the entire disk now.
21650 			 */
21651 			bcopy(&un->un_g, dkgp, sizeof (*dkgp));
21652 			dkgp->dkg_acyl = 0;
21653 			dkgp->dkg_ncyl = un->un_blockcount /
21654 			    (dkgp->dkg_nhead * dkgp->dkg_nsect);
21655 		} else {
21656 			bzero(dkgp, sizeof (struct dk_geom));
21657 			/*
21658 			 * This disk does not have a Solaris VTOC
21659 			 * so we must present a physical geometry
21660 			 * that will remain consistent regardless
21661 			 * of how the disk is used. This will ensure
21662 			 * that the geometry does not change regardless
21663 			 * of the fdisk partition type (ie. EFI, FAT32,
21664 			 * Solaris, etc).
21665 			 */
21666 			if (ISCD(un)) {
21667 				dkgp->dkg_nhead = un->un_pgeom.g_nhead;
21668 				dkgp->dkg_nsect = un->un_pgeom.g_nsect;
21669 				dkgp->dkg_ncyl = un->un_pgeom.g_ncyl;
21670 				dkgp->dkg_acyl = un->un_pgeom.g_acyl;
21671 			} else {
21672 				/*
21673 				 * Invalid un_blockcount can generate invalid
21674 				 * dk_geom and may result in division by zero
21675 				 * system failure. Should make sure blockcount
21676 				 * is valid before using it here.
21677 				 */
21678 				if (un->un_f_blockcount_is_valid == FALSE) {
21679 					mutex_exit(SD_MUTEX(un));
21680 					err = EIO;
21681 
21682 					break;
21683 				}
21684 				sd_convert_geometry(un->un_blockcount, dkgp);
21685 				dkgp->dkg_acyl = 0;
21686 				dkgp->dkg_ncyl = un->un_blockcount /
21687 				    (dkgp->dkg_nhead * dkgp->dkg_nsect);
21688 			}
21689 		}
21690 		dkgp->dkg_pcyl = dkgp->dkg_ncyl + dkgp->dkg_acyl;
21691 
21692 		if (ddi_copyout(dkgp, (void *)arg,
21693 		    sizeof (struct dk_geom), flag)) {
21694 			mutex_exit(SD_MUTEX(un));
21695 			err = EFAULT;
21696 		} else {
21697 			mutex_exit(SD_MUTEX(un));
21698 			err = 0;
21699 		}
21700 #else
21701 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCG_PHYGEOM\n");
21702 		err = ENOTTY;
21703 #endif
21704 		break;
21705 	}
21706 
21707 	case DKIOCG_VIRTGEOM: {
21708 		/* Return the driver's notion of the media's logical geometry */
21709 #if defined(__i386) || defined(__amd64)
21710 		struct dk_geom	disk_geom;
21711 		struct dk_geom	*dkgp = &disk_geom;
21712 
21713 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCG_VIRTGEOM\n");
21714 		mutex_enter(SD_MUTEX(un));
21715 		/*
21716 		 * If there is no HBA geometry available, or
21717 		 * if the HBA returned us something that doesn't
21718 		 * really fit into an Int 13/function 8 geometry
21719 		 * result, just fail the ioctl.  See PSARC 1998/313.
21720 		 */
21721 		if (un->un_lgeom.g_nhead == 0 ||
21722 		    un->un_lgeom.g_nsect == 0 ||
21723 		    un->un_lgeom.g_ncyl > 1024) {
21724 			mutex_exit(SD_MUTEX(un));
21725 			err = EINVAL;
21726 		} else {
21727 			dkgp->dkg_ncyl	= un->un_lgeom.g_ncyl;
21728 			dkgp->dkg_acyl	= un->un_lgeom.g_acyl;
21729 			dkgp->dkg_pcyl	= dkgp->dkg_ncyl + dkgp->dkg_acyl;
21730 			dkgp->dkg_nhead	= un->un_lgeom.g_nhead;
21731 			dkgp->dkg_nsect	= un->un_lgeom.g_nsect;
21732 
21733 			if (ddi_copyout(dkgp, (void *)arg,
21734 			    sizeof (struct dk_geom), flag)) {
21735 				mutex_exit(SD_MUTEX(un));
21736 				err = EFAULT;
21737 			} else {
21738 				mutex_exit(SD_MUTEX(un));
21739 				err = 0;
21740 			}
21741 		}
21742 #else
21743 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCG_VIRTGEOM\n");
21744 		err = ENOTTY;
21745 #endif
21746 		break;
21747 	}
21748 #ifdef SDDEBUG
21749 /* RESET/ABORTS testing ioctls */
21750 	case DKIOCRESET: {
21751 		int	reset_level;
21752 
21753 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
21754 			err = EFAULT;
21755 		} else {
21756 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
21757 			    "reset_level = 0x%lx\n", reset_level);
21758 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
21759 				err = 0;
21760 			} else {
21761 				err = EIO;
21762 			}
21763 		}
21764 		break;
21765 	}
21766 
21767 	case DKIOCABORT:
21768 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
21769 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
21770 			err = 0;
21771 		} else {
21772 			err = EIO;
21773 		}
21774 		break;
21775 #endif
21776 
21777 #ifdef SD_FAULT_INJECTION
21778 /* SDIOC FaultInjection testing ioctls */
21779 	case SDIOCSTART:
21780 	case SDIOCSTOP:
21781 	case SDIOCINSERTPKT:
21782 	case SDIOCINSERTXB:
21783 	case SDIOCINSERTUN:
21784 	case SDIOCINSERTARQ:
21785 	case SDIOCPUSH:
21786 	case SDIOCRETRIEVE:
21787 	case SDIOCRUN:
21788 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
21789 		    "SDIOC detected cmd:0x%X:\n", cmd);
21790 		/* call error generator */
21791 		sd_faultinjection_ioctl(cmd, arg, un);
21792 		err = 0;
21793 		break;
21794 
21795 #endif /* SD_FAULT_INJECTION */
21796 
21797 	case DKIOCFLUSHWRITECACHE:
21798 		{
21799 			struct dk_callback *dkc = (struct dk_callback *)arg;
21800 
21801 			mutex_enter(SD_MUTEX(un));
21802 			if (!un->un_f_sync_cache_supported ||
21803 			    !un->un_f_write_cache_enabled) {
21804 				err = un->un_f_sync_cache_supported ?
21805 					0 : ENOTSUP;
21806 				mutex_exit(SD_MUTEX(un));
21807 				if ((flag & FKIOCTL) && dkc != NULL &&
21808 				    dkc->dkc_callback != NULL) {
21809 					(*dkc->dkc_callback)(dkc->dkc_cookie,
21810 					    err);
21811 					/*
21812 					 * Did callback and reported error.
21813 					 * Since we did a callback, ioctl
21814 					 * should return 0.
21815 					 */
21816 					err = 0;
21817 				}
21818 				break;
21819 			}
21820 			mutex_exit(SD_MUTEX(un));
21821 
21822 			if ((flag & FKIOCTL) && dkc != NULL &&
21823 			    dkc->dkc_callback != NULL) {
21824 				/* async SYNC CACHE request */
21825 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
21826 			} else {
21827 				/* synchronous SYNC CACHE request */
21828 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
21829 			}
21830 		}
21831 		break;
21832 
21833 	case DKIOCGETWCE: {
21834 
21835 		int wce;
21836 
21837 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
21838 			break;
21839 		}
21840 
21841 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
21842 			err = EFAULT;
21843 		}
21844 		break;
21845 	}
21846 
21847 	case DKIOCSETWCE: {
21848 
21849 		int wce, sync_supported;
21850 
21851 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
21852 			err = EFAULT;
21853 			break;
21854 		}
21855 
21856 		/*
21857 		 * Synchronize multiple threads trying to enable
21858 		 * or disable the cache via the un_f_wcc_cv
21859 		 * condition variable.
21860 		 */
21861 		mutex_enter(SD_MUTEX(un));
21862 
21863 		/*
21864 		 * Don't allow the cache to be enabled if the
21865 		 * config file has it disabled.
21866 		 */
21867 		if (un->un_f_opt_disable_cache && wce) {
21868 			mutex_exit(SD_MUTEX(un));
21869 			err = EINVAL;
21870 			break;
21871 		}
21872 
21873 		/*
21874 		 * Wait for write cache change in progress
21875 		 * bit to be clear before proceeding.
21876 		 */
21877 		while (un->un_f_wcc_inprog)
21878 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
21879 
21880 		un->un_f_wcc_inprog = 1;
21881 
21882 		if (un->un_f_write_cache_enabled && wce == 0) {
21883 			/*
21884 			 * Disable the write cache.  Don't clear
21885 			 * un_f_write_cache_enabled until after
21886 			 * the mode select and flush are complete.
21887 			 */
21888 			sync_supported = un->un_f_sync_cache_supported;
21889 			mutex_exit(SD_MUTEX(un));
21890 			if ((err = sd_cache_control(un, SD_CACHE_NOCHANGE,
21891 			    SD_CACHE_DISABLE)) == 0 && sync_supported) {
21892 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
21893 			}
21894 
21895 			mutex_enter(SD_MUTEX(un));
21896 			if (err == 0) {
21897 				un->un_f_write_cache_enabled = 0;
21898 			}
21899 
21900 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
21901 			/*
21902 			 * Set un_f_write_cache_enabled first, so there is
21903 			 * no window where the cache is enabled, but the
21904 			 * bit says it isn't.
21905 			 */
21906 			un->un_f_write_cache_enabled = 1;
21907 			mutex_exit(SD_MUTEX(un));
21908 
21909 			err = sd_cache_control(un, SD_CACHE_NOCHANGE,
21910 				SD_CACHE_ENABLE);
21911 
21912 			mutex_enter(SD_MUTEX(un));
21913 
21914 			if (err) {
21915 				un->un_f_write_cache_enabled = 0;
21916 			}
21917 		}
21918 
21919 		un->un_f_wcc_inprog = 0;
21920 		cv_broadcast(&un->un_wcc_cv);
21921 		mutex_exit(SD_MUTEX(un));
21922 		break;
21923 	}
21924 
21925 	default:
21926 		err = ENOTTY;
21927 		break;
21928 	}
21929 	mutex_enter(SD_MUTEX(un));
21930 	un->un_ncmds_in_driver--;
21931 	ASSERT(un->un_ncmds_in_driver >= 0);
21932 	mutex_exit(SD_MUTEX(un));
21933 
21934 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
21935 	return (err);
21936 }
21937 
21938 
21939 /*
21940  *    Function: sd_uscsi_ioctl
21941  *
21942  * Description: This routine is the driver entry point for handling USCSI ioctl
21943  *		requests (USCSICMD).
21944  *
21945  *   Arguments: dev	- the device number
21946  *		arg	- user provided scsi command
21947  *		flag	- this argument is a pass through to ddi_copyxxx()
21948  *			  directly from the mode argument of ioctl().
21949  *
21950  * Return Code: code returned by sd_send_scsi_cmd
21951  *		ENXIO
21952  *		EFAULT
21953  *		EAGAIN
21954  */
21955 
21956 static int
21957 sd_uscsi_ioctl(dev_t dev, caddr_t arg, int flag)
21958 {
21959 #ifdef _MULTI_DATAMODEL
21960 	/*
21961 	 * For use when a 32 bit app makes a call into a
21962 	 * 64 bit ioctl
21963 	 */
21964 	struct uscsi_cmd32	uscsi_cmd_32_for_64;
21965 	struct uscsi_cmd32	*ucmd32 = &uscsi_cmd_32_for_64;
21966 	model_t			model;
21967 #endif /* _MULTI_DATAMODEL */
21968 	struct uscsi_cmd	*scmd = NULL;
21969 	struct sd_lun		*un = NULL;
21970 	enum uio_seg		uioseg;
21971 	char			cdb[CDB_GROUP0];
21972 	int			rval = 0;
21973 
21974 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21975 		return (ENXIO);
21976 	}
21977 
21978 	SD_TRACE(SD_LOG_IOCTL, un, "sd_uscsi_ioctl: entry: un:0x%p\n", un);
21979 
21980 	scmd = (struct uscsi_cmd *)
21981 	    kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
21982 
21983 #ifdef _MULTI_DATAMODEL
21984 	switch (model = ddi_model_convert_from(flag & FMODELS)) {
21985 	case DDI_MODEL_ILP32:
21986 	{
21987 		if (ddi_copyin((void *)arg, ucmd32, sizeof (*ucmd32), flag)) {
21988 			rval = EFAULT;
21989 			goto done;
21990 		}
21991 		/*
21992 		 * Convert the ILP32 uscsi data from the
21993 		 * application to LP64 for internal use.
21994 		 */
21995 		uscsi_cmd32touscsi_cmd(ucmd32, scmd);
21996 		break;
21997 	}
21998 	case DDI_MODEL_NONE:
21999 		if (ddi_copyin((void *)arg, scmd, sizeof (*scmd), flag)) {
22000 			rval = EFAULT;
22001 			goto done;
22002 		}
22003 		break;
22004 	}
22005 #else /* ! _MULTI_DATAMODEL */
22006 	if (ddi_copyin((void *)arg, scmd, sizeof (*scmd), flag)) {
22007 		rval = EFAULT;
22008 		goto done;
22009 	}
22010 #endif /* _MULTI_DATAMODEL */
22011 
22012 	scmd->uscsi_flags &= ~USCSI_NOINTR;
22013 	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
22014 	if (un->un_f_format_in_progress == TRUE) {
22015 		rval = EAGAIN;
22016 		goto done;
22017 	}
22018 
22019 	/*
22020 	 * Gotta do the ddi_copyin() here on the uscsi_cdb so that
22021 	 * we will have a valid cdb[0] to test.
22022 	 */
22023 	if ((ddi_copyin(scmd->uscsi_cdb, cdb, CDB_GROUP0, flag) == 0) &&
22024 	    (cdb[0] == SCMD_FORMAT)) {
22025 		SD_TRACE(SD_LOG_IOCTL, un,
22026 		    "sd_uscsi_ioctl: scmd->uscsi_cdb 0x%x\n", cdb[0]);
22027 		mutex_enter(SD_MUTEX(un));
22028 		un->un_f_format_in_progress = TRUE;
22029 		mutex_exit(SD_MUTEX(un));
22030 		rval = sd_send_scsi_cmd(dev, scmd, uioseg, uioseg, uioseg,
22031 		    SD_PATH_STANDARD);
22032 		mutex_enter(SD_MUTEX(un));
22033 		un->un_f_format_in_progress = FALSE;
22034 		mutex_exit(SD_MUTEX(un));
22035 	} else {
22036 		SD_TRACE(SD_LOG_IOCTL, un,
22037 		    "sd_uscsi_ioctl: scmd->uscsi_cdb 0x%x\n", cdb[0]);
22038 		/*
22039 		 * It's OK to fall into here even if the ddi_copyin()
22040 		 * on the uscsi_cdb above fails, because sd_send_scsi_cmd()
22041 		 * does this same copyin and will return the EFAULT
22042 		 * if it fails.
22043 		 */
22044 		rval = sd_send_scsi_cmd(dev, scmd, uioseg, uioseg, uioseg,
22045 		    SD_PATH_STANDARD);
22046 	}
22047 #ifdef _MULTI_DATAMODEL
22048 	switch (model) {
22049 	case DDI_MODEL_ILP32:
22050 		/*
22051 		 * Convert back to ILP32 before copyout to the
22052 		 * application
22053 		 */
22054 		uscsi_cmdtouscsi_cmd32(scmd, ucmd32);
22055 		if (ddi_copyout(ucmd32, (void *)arg, sizeof (*ucmd32), flag)) {
22056 			if (rval != 0) {
22057 				rval = EFAULT;
22058 			}
22059 		}
22060 		break;
22061 	case DDI_MODEL_NONE:
22062 		if (ddi_copyout(scmd, (void *)arg, sizeof (*scmd), flag)) {
22063 			if (rval != 0) {
22064 				rval = EFAULT;
22065 			}
22066 		}
22067 		break;
22068 	}
22069 #else /* ! _MULTI_DATAMODE */
22070 	if (ddi_copyout(scmd, (void *)arg, sizeof (*scmd), flag)) {
22071 		if (rval != 0) {
22072 			rval = EFAULT;
22073 		}
22074 	}
22075 #endif /* _MULTI_DATAMODE */
22076 done:
22077 	kmem_free(scmd, sizeof (struct uscsi_cmd));
22078 
22079 	SD_TRACE(SD_LOG_IOCTL, un, "sd_uscsi_ioctl: exit: un:0x%p\n", un);
22080 
22081 	return (rval);
22082 }
22083 
22084 
22085 /*
22086  *    Function: sd_dkio_ctrl_info
22087  *
22088  * Description: This routine is the driver entry point for handling controller
22089  *		information ioctl requests (DKIOCINFO).
22090  *
22091  *   Arguments: dev  - the device number
22092  *		arg  - pointer to user provided dk_cinfo structure
22093  *		       specifying the controller type and attributes.
22094  *		flag - this argument is a pass through to ddi_copyxxx()
22095  *		       directly from the mode argument of ioctl().
22096  *
22097  * Return Code: 0
22098  *		EFAULT
22099  *		ENXIO
22100  */
22101 
22102 static int
22103 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
22104 {
22105 	struct sd_lun	*un = NULL;
22106 	struct dk_cinfo	*info;
22107 	dev_info_t	*pdip;
22108 	int		lun, tgt;
22109 
22110 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22111 		return (ENXIO);
22112 	}
22113 
22114 	info = (struct dk_cinfo *)
22115 		kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
22116 
22117 	switch (un->un_ctype) {
22118 	case CTYPE_CDROM:
22119 		info->dki_ctype = DKC_CDROM;
22120 		break;
22121 	default:
22122 		info->dki_ctype = DKC_SCSI_CCS;
22123 		break;
22124 	}
22125 	pdip = ddi_get_parent(SD_DEVINFO(un));
22126 	info->dki_cnum = ddi_get_instance(pdip);
22127 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
22128 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
22129 	} else {
22130 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
22131 		    DK_DEVLEN - 1);
22132 	}
22133 
22134 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22135 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
22136 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22137 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
22138 
22139 	/* Unit Information */
22140 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
22141 	info->dki_slave = ((tgt << 3) | lun);
22142 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
22143 	    DK_DEVLEN - 1);
22144 	info->dki_flags = DKI_FMTVOL;
22145 	info->dki_partition = SDPART(dev);
22146 
22147 	/* Max Transfer size of this device in blocks */
22148 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
22149 	info->dki_addr = 0;
22150 	info->dki_space = 0;
22151 	info->dki_prio = 0;
22152 	info->dki_vec = 0;
22153 
22154 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
22155 		kmem_free(info, sizeof (struct dk_cinfo));
22156 		return (EFAULT);
22157 	} else {
22158 		kmem_free(info, sizeof (struct dk_cinfo));
22159 		return (0);
22160 	}
22161 }
22162 
22163 
22164 /*
22165  *    Function: sd_get_media_info
22166  *
22167  * Description: This routine is the driver entry point for handling ioctl
22168  *		requests for the media type or command set profile used by the
22169  *		drive to operate on the media (DKIOCGMEDIAINFO).
22170  *
22171  *   Arguments: dev	- the device number
22172  *		arg	- pointer to user provided dk_minfo structure
22173  *			  specifying the media type, logical block size and
22174  *			  drive capacity.
22175  *		flag	- this argument is a pass through to ddi_copyxxx()
22176  *			  directly from the mode argument of ioctl().
22177  *
22178  * Return Code: 0
22179  *		EACCESS
22180  *		EFAULT
22181  *		ENXIO
22182  *		EIO
22183  */
22184 
22185 static int
22186 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
22187 {
22188 	struct sd_lun		*un = NULL;
22189 	struct uscsi_cmd	com;
22190 	struct scsi_inquiry	*sinq;
22191 	struct dk_minfo		media_info;
22192 	u_longlong_t		media_capacity;
22193 	uint64_t		capacity;
22194 	uint_t			lbasize;
22195 	uchar_t			*out_data;
22196 	uchar_t			*rqbuf;
22197 	int			rval = 0;
22198 	int			rtn;
22199 
22200 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
22201 	    (un->un_state == SD_STATE_OFFLINE)) {
22202 		return (ENXIO);
22203 	}
22204 
22205 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
22206 
22207 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
22208 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
22209 
22210 	/* Issue a TUR to determine if the drive is ready with media present */
22211 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
22212 	if (rval == ENXIO) {
22213 		goto done;
22214 	}
22215 
22216 	/* Now get configuration data */
22217 	if (ISCD(un)) {
22218 		media_info.dki_media_type = DK_CDROM;
22219 
22220 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
22221 		if (un->un_f_mmc_cap == TRUE) {
22222 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
22223 				SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN);
22224 
22225 			if (rtn) {
22226 				/*
22227 				 * Failed for other than an illegal request
22228 				 * or command not supported
22229 				 */
22230 				if ((com.uscsi_status == STATUS_CHECK) &&
22231 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
22232 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
22233 					    (rqbuf[12] != 0x20)) {
22234 						rval = EIO;
22235 						goto done;
22236 					}
22237 				}
22238 			} else {
22239 				/*
22240 				 * The GET CONFIGURATION command succeeded
22241 				 * so set the media type according to the
22242 				 * returned data
22243 				 */
22244 				media_info.dki_media_type = out_data[6];
22245 				media_info.dki_media_type <<= 8;
22246 				media_info.dki_media_type |= out_data[7];
22247 			}
22248 		}
22249 	} else {
22250 		/*
22251 		 * The profile list is not available, so we attempt to identify
22252 		 * the media type based on the inquiry data
22253 		 */
22254 		sinq = un->un_sd->sd_inq;
22255 		if (sinq->inq_qual == 0) {
22256 			/* This is a direct access device */
22257 			media_info.dki_media_type = DK_FIXED_DISK;
22258 
22259 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
22260 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
22261 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
22262 					media_info.dki_media_type = DK_ZIP;
22263 				} else if (
22264 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
22265 					media_info.dki_media_type = DK_JAZ;
22266 				}
22267 			}
22268 		} else {
22269 			/* Not a CD or direct access so return unknown media */
22270 			media_info.dki_media_type = DK_UNKNOWN;
22271 		}
22272 	}
22273 
22274 	/* Now read the capacity so we can provide the lbasize and capacity */
22275 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
22276 	    SD_PATH_DIRECT)) {
22277 	case 0:
22278 		break;
22279 	case EACCES:
22280 		rval = EACCES;
22281 		goto done;
22282 	default:
22283 		rval = EIO;
22284 		goto done;
22285 	}
22286 
22287 	media_info.dki_lbsize = lbasize;
22288 	media_capacity = capacity;
22289 
22290 	/*
22291 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
22292 	 * un->un_sys_blocksize chunks. So we need to convert it into
22293 	 * cap.lbasize chunks.
22294 	 */
22295 	media_capacity *= un->un_sys_blocksize;
22296 	media_capacity /= lbasize;
22297 	media_info.dki_capacity = media_capacity;
22298 
22299 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
22300 		rval = EFAULT;
22301 		/* Put goto. Anybody might add some code below in future */
22302 		goto done;
22303 	}
22304 done:
22305 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
22306 	kmem_free(rqbuf, SENSE_LENGTH);
22307 	return (rval);
22308 }
22309 
22310 
22311 /*
22312  *    Function: sd_dkio_get_geometry
22313  *
22314  * Description: This routine is the driver entry point for handling user
22315  *		requests to get the device geometry (DKIOCGGEOM).
22316  *
22317  *   Arguments: dev  - the device number
22318  *		arg  - pointer to user provided dk_geom structure specifying
22319  *			the controller's notion of the current geometry.
22320  *		flag - this argument is a pass through to ddi_copyxxx()
22321  *		       directly from the mode argument of ioctl().
22322  *		geom_validated - flag indicating if the device geometry has been
22323  *				 previously validated in the sdioctl routine.
22324  *
22325  * Return Code: 0
22326  *		EFAULT
22327  *		ENXIO
22328  *		EIO
22329  */
22330 
22331 static int
22332 sd_dkio_get_geometry(dev_t dev, caddr_t arg, int flag, int geom_validated)
22333 {
22334 	struct sd_lun	*un = NULL;
22335 	struct dk_geom	*tmp_geom = NULL;
22336 	int		rval = 0;
22337 
22338 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22339 		return (ENXIO);
22340 	}
22341 
22342 #if defined(__i386) || defined(__amd64)
22343 	if (un->un_solaris_size == 0) {
22344 		return (EIO);
22345 	}
22346 #endif
22347 	if (geom_validated == FALSE) {
22348 		/*
22349 		 * sd_validate_geometry does not spin a disk up
22350 		 * if it was spun down. We need to make sure it
22351 		 * is ready.
22352 		 */
22353 		if ((rval = sd_send_scsi_TEST_UNIT_READY(un, 0)) != 0) {
22354 			return (rval);
22355 		}
22356 		mutex_enter(SD_MUTEX(un));
22357 		rval = sd_validate_geometry(un, SD_PATH_DIRECT);
22358 		mutex_exit(SD_MUTEX(un));
22359 	}
22360 	if (rval)
22361 		return (rval);
22362 
22363 	/*
22364 	 * Make a local copy of the soft state geometry to avoid some potential
22365 	 * race conditions associated with holding the mutex and updating the
22366 	 * write_reinstruct value
22367 	 */
22368 	tmp_geom = kmem_zalloc(sizeof (struct dk_geom), KM_SLEEP);
22369 	mutex_enter(SD_MUTEX(un));
22370 	bcopy(&un->un_g, tmp_geom, sizeof (struct dk_geom));
22371 	mutex_exit(SD_MUTEX(un));
22372 
22373 	if (tmp_geom->dkg_write_reinstruct == 0) {
22374 		tmp_geom->dkg_write_reinstruct =
22375 		    (int)((int)(tmp_geom->dkg_nsect * tmp_geom->dkg_rpm *
22376 		    sd_rot_delay) / (int)60000);
22377 	}
22378 
22379 	rval = ddi_copyout(tmp_geom, (void *)arg, sizeof (struct dk_geom),
22380 	    flag);
22381 	if (rval != 0) {
22382 		rval = EFAULT;
22383 	}
22384 
22385 	kmem_free(tmp_geom, sizeof (struct dk_geom));
22386 	return (rval);
22387 
22388 }
22389 
22390 
22391 /*
22392  *    Function: sd_dkio_set_geometry
22393  *
22394  * Description: This routine is the driver entry point for handling user
22395  *		requests to set the device geometry (DKIOCSGEOM). The actual
22396  *		device geometry is not updated, just the driver "notion" of it.
22397  *
22398  *   Arguments: dev  - the device number
22399  *		arg  - pointer to user provided dk_geom structure used to set
22400  *			the controller's notion of the current geometry.
22401  *		flag - this argument is a pass through to ddi_copyxxx()
22402  *		       directly from the mode argument of ioctl().
22403  *
22404  * Return Code: 0
22405  *		EFAULT
22406  *		ENXIO
22407  *		EIO
22408  */
22409 
22410 static int
22411 sd_dkio_set_geometry(dev_t dev, caddr_t arg, int flag)
22412 {
22413 	struct sd_lun	*un = NULL;
22414 	struct dk_geom	*tmp_geom;
22415 	struct dk_map	*lp;
22416 	int		rval = 0;
22417 	int		i;
22418 
22419 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22420 		return (ENXIO);
22421 	}
22422 
22423 #if defined(__i386) || defined(__amd64)
22424 	if (un->un_solaris_size == 0) {
22425 		return (EIO);
22426 	}
22427 #endif
22428 	/*
22429 	 * We need to copy the user specified geometry into local
22430 	 * storage and then update the softstate. We don't want to hold
22431 	 * the mutex and copyin directly from the user to the soft state
22432 	 */
22433 	tmp_geom = (struct dk_geom *)
22434 	    kmem_zalloc(sizeof (struct dk_geom), KM_SLEEP);
22435 	rval = ddi_copyin(arg, tmp_geom, sizeof (struct dk_geom), flag);
22436 	if (rval != 0) {
22437 		kmem_free(tmp_geom, sizeof (struct dk_geom));
22438 		return (EFAULT);
22439 	}
22440 
22441 	mutex_enter(SD_MUTEX(un));
22442 	bcopy(tmp_geom, &un->un_g, sizeof (struct dk_geom));
22443 	for (i = 0; i < NDKMAP; i++) {
22444 		lp  = &un->un_map[i];
22445 		un->un_offset[i] =
22446 		    un->un_g.dkg_nhead * un->un_g.dkg_nsect * lp->dkl_cylno;
22447 #if defined(__i386) || defined(__amd64)
22448 		un->un_offset[i] += un->un_solaris_offset;
22449 #endif
22450 	}
22451 	un->un_f_geometry_is_valid = FALSE;
22452 	mutex_exit(SD_MUTEX(un));
22453 	kmem_free(tmp_geom, sizeof (struct dk_geom));
22454 
22455 	return (rval);
22456 }
22457 
22458 
22459 /*
22460  *    Function: sd_dkio_get_partition
22461  *
22462  * Description: This routine is the driver entry point for handling user
22463  *		requests to get the partition table (DKIOCGAPART).
22464  *
22465  *   Arguments: dev  - the device number
22466  *		arg  - pointer to user provided dk_allmap structure specifying
22467  *			the controller's notion of the current partition table.
22468  *		flag - this argument is a pass through to ddi_copyxxx()
22469  *		       directly from the mode argument of ioctl().
22470  *		geom_validated - flag indicating if the device geometry has been
22471  *				 previously validated in the sdioctl routine.
22472  *
22473  * Return Code: 0
22474  *		EFAULT
22475  *		ENXIO
22476  *		EIO
22477  */
22478 
22479 static int
22480 sd_dkio_get_partition(dev_t dev, caddr_t arg, int flag, int geom_validated)
22481 {
22482 	struct sd_lun	*un = NULL;
22483 	int		rval = 0;
22484 	int		size;
22485 
22486 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22487 		return (ENXIO);
22488 	}
22489 
22490 #if defined(__i386) || defined(__amd64)
22491 	if (un->un_solaris_size == 0) {
22492 		return (EIO);
22493 	}
22494 #endif
22495 	/*
22496 	 * Make sure the geometry is valid before getting the partition
22497 	 * information.
22498 	 */
22499 	mutex_enter(SD_MUTEX(un));
22500 	if (geom_validated == FALSE) {
22501 		/*
22502 		 * sd_validate_geometry does not spin a disk up
22503 		 * if it was spun down. We need to make sure it
22504 		 * is ready before validating the geometry.
22505 		 */
22506 		mutex_exit(SD_MUTEX(un));
22507 		if ((rval = sd_send_scsi_TEST_UNIT_READY(un, 0)) != 0) {
22508 			return (rval);
22509 		}
22510 		mutex_enter(SD_MUTEX(un));
22511 
22512 		if ((rval = sd_validate_geometry(un, SD_PATH_DIRECT)) != 0) {
22513 			mutex_exit(SD_MUTEX(un));
22514 			return (rval);
22515 		}
22516 	}
22517 	mutex_exit(SD_MUTEX(un));
22518 
22519 #ifdef _MULTI_DATAMODEL
22520 	switch (ddi_model_convert_from(flag & FMODELS)) {
22521 	case DDI_MODEL_ILP32: {
22522 		struct dk_map32 dk_map32[NDKMAP];
22523 		int		i;
22524 
22525 		for (i = 0; i < NDKMAP; i++) {
22526 			dk_map32[i].dkl_cylno = un->un_map[i].dkl_cylno;
22527 			dk_map32[i].dkl_nblk  = un->un_map[i].dkl_nblk;
22528 		}
22529 		size = NDKMAP * sizeof (struct dk_map32);
22530 		rval = ddi_copyout(dk_map32, (void *)arg, size, flag);
22531 		if (rval != 0) {
22532 			rval = EFAULT;
22533 		}
22534 		break;
22535 	}
22536 	case DDI_MODEL_NONE:
22537 		size = NDKMAP * sizeof (struct dk_map);
22538 		rval = ddi_copyout(un->un_map, (void *)arg, size, flag);
22539 		if (rval != 0) {
22540 			rval = EFAULT;
22541 		}
22542 		break;
22543 	}
22544 #else /* ! _MULTI_DATAMODEL */
22545 	size = NDKMAP * sizeof (struct dk_map);
22546 	rval = ddi_copyout(un->un_map, (void *)arg, size, flag);
22547 	if (rval != 0) {
22548 		rval = EFAULT;
22549 	}
22550 #endif /* _MULTI_DATAMODEL */
22551 	return (rval);
22552 }
22553 
22554 
22555 /*
22556  *    Function: sd_dkio_set_partition
22557  *
22558  * Description: This routine is the driver entry point for handling user
22559  *		requests to set the partition table (DKIOCSAPART). The actual
22560  *		device partition is not updated.
22561  *
22562  *   Arguments: dev  - the device number
22563  *		arg  - pointer to user provided dk_allmap structure used to set
22564  *			the controller's notion of the partition table.
22565  *		flag - this argument is a pass through to ddi_copyxxx()
22566  *		       directly from the mode argument of ioctl().
22567  *
22568  * Return Code: 0
22569  *		EINVAL
22570  *		EFAULT
22571  *		ENXIO
22572  *		EIO
22573  */
22574 
22575 static int
22576 sd_dkio_set_partition(dev_t dev, caddr_t arg, int flag)
22577 {
22578 	struct sd_lun	*un = NULL;
22579 	struct dk_map	dk_map[NDKMAP];
22580 	struct dk_map	*lp;
22581 	int		rval = 0;
22582 	int		size;
22583 	int		i;
22584 #if defined(_SUNOS_VTOC_16)
22585 	struct dkl_partition	*vp;
22586 #endif
22587 
22588 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22589 		return (ENXIO);
22590 	}
22591 
22592 	/*
22593 	 * Set the map for all logical partitions.  We lock
22594 	 * the priority just to make sure an interrupt doesn't
22595 	 * come in while the map is half updated.
22596 	 */
22597 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_solaris_size))
22598 	mutex_enter(SD_MUTEX(un));
22599 	if (un->un_blockcount > DK_MAX_BLOCKS) {
22600 		mutex_exit(SD_MUTEX(un));
22601 		return (ENOTSUP);
22602 	}
22603 	mutex_exit(SD_MUTEX(un));
22604 	if (un->un_solaris_size == 0) {
22605 		return (EIO);
22606 	}
22607 
22608 #ifdef _MULTI_DATAMODEL
22609 	switch (ddi_model_convert_from(flag & FMODELS)) {
22610 	case DDI_MODEL_ILP32: {
22611 		struct dk_map32 dk_map32[NDKMAP];
22612 
22613 		size = NDKMAP * sizeof (struct dk_map32);
22614 		rval = ddi_copyin((void *)arg, dk_map32, size, flag);
22615 		if (rval != 0) {
22616 			return (EFAULT);
22617 		}
22618 		for (i = 0; i < NDKMAP; i++) {
22619 			dk_map[i].dkl_cylno = dk_map32[i].dkl_cylno;
22620 			dk_map[i].dkl_nblk  = dk_map32[i].dkl_nblk;
22621 		}
22622 		break;
22623 	}
22624 	case DDI_MODEL_NONE:
22625 		size = NDKMAP * sizeof (struct dk_map);
22626 		rval = ddi_copyin((void *)arg, dk_map, size, flag);
22627 		if (rval != 0) {
22628 			return (EFAULT);
22629 		}
22630 		break;
22631 	}
22632 #else /* ! _MULTI_DATAMODEL */
22633 	size = NDKMAP * sizeof (struct dk_map);
22634 	rval = ddi_copyin((void *)arg, dk_map, size, flag);
22635 	if (rval != 0) {
22636 		return (EFAULT);
22637 	}
22638 #endif /* _MULTI_DATAMODEL */
22639 
22640 	mutex_enter(SD_MUTEX(un));
22641 	/* Note: The size used in this bcopy is set based upon the data model */
22642 	bcopy(dk_map, un->un_map, size);
22643 #if defined(_SUNOS_VTOC_16)
22644 	vp = (struct dkl_partition *)&(un->un_vtoc);
22645 #endif	/* defined(_SUNOS_VTOC_16) */
22646 	for (i = 0; i < NDKMAP; i++) {
22647 		lp  = &un->un_map[i];
22648 		un->un_offset[i] =
22649 		    un->un_g.dkg_nhead * un->un_g.dkg_nsect * lp->dkl_cylno;
22650 #if defined(_SUNOS_VTOC_16)
22651 		vp->p_start = un->un_offset[i];
22652 		vp->p_size = lp->dkl_nblk;
22653 		vp++;
22654 #endif	/* defined(_SUNOS_VTOC_16) */
22655 #if defined(__i386) || defined(__amd64)
22656 		un->un_offset[i] += un->un_solaris_offset;
22657 #endif
22658 	}
22659 	mutex_exit(SD_MUTEX(un));
22660 	return (rval);
22661 }
22662 
22663 
22664 /*
22665  *    Function: sd_dkio_get_vtoc
22666  *
22667  * Description: This routine is the driver entry point for handling user
22668  *		requests to get the current volume table of contents
22669  *		(DKIOCGVTOC).
22670  *
22671  *   Arguments: dev  - the device number
22672  *		arg  - pointer to user provided vtoc structure specifying
22673  *			the current vtoc.
22674  *		flag - this argument is a pass through to ddi_copyxxx()
22675  *		       directly from the mode argument of ioctl().
22676  *		geom_validated - flag indicating if the device geometry has been
22677  *				 previously validated in the sdioctl routine.
22678  *
22679  * Return Code: 0
22680  *		EFAULT
22681  *		ENXIO
22682  *		EIO
22683  */
22684 
22685 static int
22686 sd_dkio_get_vtoc(dev_t dev, caddr_t arg, int flag, int geom_validated)
22687 {
22688 	struct sd_lun	*un = NULL;
22689 #if defined(_SUNOS_VTOC_8)
22690 	struct vtoc	user_vtoc;
22691 #endif	/* defined(_SUNOS_VTOC_8) */
22692 	int		rval = 0;
22693 
22694 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22695 		return (ENXIO);
22696 	}
22697 
22698 	mutex_enter(SD_MUTEX(un));
22699 	if (geom_validated == FALSE) {
22700 		/*
22701 		 * sd_validate_geometry does not spin a disk up
22702 		 * if it was spun down. We need to make sure it
22703 		 * is ready.
22704 		 */
22705 		mutex_exit(SD_MUTEX(un));
22706 		if ((rval = sd_send_scsi_TEST_UNIT_READY(un, 0)) != 0) {
22707 			return (rval);
22708 		}
22709 		mutex_enter(SD_MUTEX(un));
22710 		if ((rval = sd_validate_geometry(un, SD_PATH_DIRECT)) != 0) {
22711 			mutex_exit(SD_MUTEX(un));
22712 			return (rval);
22713 		}
22714 	}
22715 
22716 #if defined(_SUNOS_VTOC_8)
22717 	sd_build_user_vtoc(un, &user_vtoc);
22718 	mutex_exit(SD_MUTEX(un));
22719 
22720 #ifdef _MULTI_DATAMODEL
22721 	switch (ddi_model_convert_from(flag & FMODELS)) {
22722 	case DDI_MODEL_ILP32: {
22723 		struct vtoc32 user_vtoc32;
22724 
22725 		vtoctovtoc32(user_vtoc, user_vtoc32);
22726 		if (ddi_copyout(&user_vtoc32, (void *)arg,
22727 		    sizeof (struct vtoc32), flag)) {
22728 			return (EFAULT);
22729 		}
22730 		break;
22731 	}
22732 
22733 	case DDI_MODEL_NONE:
22734 		if (ddi_copyout(&user_vtoc, (void *)arg,
22735 		    sizeof (struct vtoc), flag)) {
22736 			return (EFAULT);
22737 		}
22738 		break;
22739 	}
22740 #else /* ! _MULTI_DATAMODEL */
22741 	if (ddi_copyout(&user_vtoc, (void *)arg, sizeof (struct vtoc), flag)) {
22742 		return (EFAULT);
22743 	}
22744 #endif /* _MULTI_DATAMODEL */
22745 
22746 #elif defined(_SUNOS_VTOC_16)
22747 	mutex_exit(SD_MUTEX(un));
22748 
22749 #ifdef _MULTI_DATAMODEL
22750 	/*
22751 	 * The un_vtoc structure is a "struct dk_vtoc"  which is always
22752 	 * 32-bit to maintain compatibility with existing on-disk
22753 	 * structures.  Thus, we need to convert the structure when copying
22754 	 * it out to a datamodel-dependent "struct vtoc" in a 64-bit
22755 	 * program.  If the target is a 32-bit program, then no conversion
22756 	 * is necessary.
22757 	 */
22758 	/* LINTED: logical expression always true: op "||" */
22759 	ASSERT(sizeof (un->un_vtoc) == sizeof (struct vtoc32));
22760 	switch (ddi_model_convert_from(flag & FMODELS)) {
22761 	case DDI_MODEL_ILP32:
22762 		if (ddi_copyout(&(un->un_vtoc), (void *)arg,
22763 		    sizeof (un->un_vtoc), flag)) {
22764 			return (EFAULT);
22765 		}
22766 		break;
22767 
22768 	case DDI_MODEL_NONE: {
22769 		struct vtoc user_vtoc;
22770 
22771 		vtoc32tovtoc(un->un_vtoc, user_vtoc);
22772 		if (ddi_copyout(&user_vtoc, (void *)arg,
22773 		    sizeof (struct vtoc), flag)) {
22774 			return (EFAULT);
22775 		}
22776 		break;
22777 	}
22778 	}
22779 #else /* ! _MULTI_DATAMODEL */
22780 	if (ddi_copyout(&(un->un_vtoc), (void *)arg, sizeof (un->un_vtoc),
22781 	    flag)) {
22782 		return (EFAULT);
22783 	}
22784 #endif /* _MULTI_DATAMODEL */
22785 #else
22786 #error "No VTOC format defined."
22787 #endif
22788 
22789 	return (rval);
22790 }
22791 
22792 static int
22793 sd_dkio_get_efi(dev_t dev, caddr_t arg, int flag)
22794 {
22795 	struct sd_lun	*un = NULL;
22796 	dk_efi_t	user_efi;
22797 	int		rval = 0;
22798 	void		*buffer;
22799 
22800 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL)
22801 		return (ENXIO);
22802 
22803 	if (ddi_copyin(arg, &user_efi, sizeof (dk_efi_t), flag))
22804 		return (EFAULT);
22805 
22806 	user_efi.dki_data = (void *)(uintptr_t)user_efi.dki_data_64;
22807 
22808 	if ((user_efi.dki_length % un->un_tgt_blocksize) ||
22809 	    (user_efi.dki_length > un->un_max_xfer_size))
22810 		return (EINVAL);
22811 
22812 	buffer = kmem_alloc(user_efi.dki_length, KM_SLEEP);
22813 	rval = sd_send_scsi_READ(un, buffer, user_efi.dki_length,
22814 	    user_efi.dki_lba, SD_PATH_DIRECT);
22815 	if (rval == 0 && ddi_copyout(buffer, user_efi.dki_data,
22816 	    user_efi.dki_length, flag) != 0)
22817 		rval = EFAULT;
22818 
22819 	kmem_free(buffer, user_efi.dki_length);
22820 	return (rval);
22821 }
22822 
22823 /*
22824  *    Function: sd_build_user_vtoc
22825  *
22826  * Description: This routine populates a pass by reference variable with the
22827  *		current volume table of contents.
22828  *
22829  *   Arguments: un - driver soft state (unit) structure
22830  *		user_vtoc - pointer to vtoc structure to be populated
22831  */
22832 
22833 static void
22834 sd_build_user_vtoc(struct sd_lun *un, struct vtoc *user_vtoc)
22835 {
22836 	struct dk_map2		*lpart;
22837 	struct dk_map		*lmap;
22838 	struct partition	*vpart;
22839 	int			nblks;
22840 	int			i;
22841 
22842 	ASSERT(mutex_owned(SD_MUTEX(un)));
22843 
22844 	/*
22845 	 * Return vtoc structure fields in the provided VTOC area, addressed
22846 	 * by *vtoc.
22847 	 */
22848 	bzero(user_vtoc, sizeof (struct vtoc));
22849 	user_vtoc->v_bootinfo[0] = un->un_vtoc.v_bootinfo[0];
22850 	user_vtoc->v_bootinfo[1] = un->un_vtoc.v_bootinfo[1];
22851 	user_vtoc->v_bootinfo[2] = un->un_vtoc.v_bootinfo[2];
22852 	user_vtoc->v_sanity	= VTOC_SANE;
22853 	user_vtoc->v_version	= un->un_vtoc.v_version;
22854 	bcopy(un->un_vtoc.v_volume, user_vtoc->v_volume, LEN_DKL_VVOL);
22855 	user_vtoc->v_sectorsz = un->un_sys_blocksize;
22856 	user_vtoc->v_nparts = un->un_vtoc.v_nparts;
22857 	bcopy(un->un_vtoc.v_reserved, user_vtoc->v_reserved,
22858 	    sizeof (un->un_vtoc.v_reserved));
22859 	/*
22860 	 * Convert partitioning information.
22861 	 *
22862 	 * Note the conversion from starting cylinder number
22863 	 * to starting sector number.
22864 	 */
22865 	lmap = un->un_map;
22866 	lpart = (struct dk_map2 *)un->un_vtoc.v_part;
22867 	vpart = user_vtoc->v_part;
22868 
22869 	nblks = un->un_g.dkg_nsect * un->un_g.dkg_nhead;
22870 
22871 	for (i = 0; i < V_NUMPAR; i++) {
22872 		vpart->p_tag	= lpart->p_tag;
22873 		vpart->p_flag	= lpart->p_flag;
22874 		vpart->p_start	= lmap->dkl_cylno * nblks;
22875 		vpart->p_size	= lmap->dkl_nblk;
22876 		lmap++;
22877 		lpart++;
22878 		vpart++;
22879 
22880 		/* (4364927) */
22881 		user_vtoc->timestamp[i] = (time_t)un->un_vtoc.v_timestamp[i];
22882 	}
22883 
22884 	bcopy(un->un_asciilabel, user_vtoc->v_asciilabel, LEN_DKL_ASCII);
22885 }
22886 
22887 static int
22888 sd_dkio_partition(dev_t dev, caddr_t arg, int flag)
22889 {
22890 	struct sd_lun		*un = NULL;
22891 	struct partition64	p64;
22892 	int			rval = 0;
22893 	uint_t			nparts;
22894 	efi_gpe_t		*partitions;
22895 	efi_gpt_t		*buffer;
22896 	diskaddr_t		gpe_lba;
22897 
22898 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22899 		return (ENXIO);
22900 	}
22901 
22902 	if (ddi_copyin((const void *)arg, &p64,
22903 	    sizeof (struct partition64), flag)) {
22904 		return (EFAULT);
22905 	}
22906 
22907 	buffer = kmem_alloc(EFI_MIN_ARRAY_SIZE, KM_SLEEP);
22908 	rval = sd_send_scsi_READ(un, buffer, DEV_BSIZE,
22909 		1, SD_PATH_DIRECT);
22910 	if (rval != 0)
22911 		goto done_error;
22912 
22913 	sd_swap_efi_gpt(buffer);
22914 
22915 	if ((rval = sd_validate_efi(buffer)) != 0)
22916 		goto done_error;
22917 
22918 	nparts = buffer->efi_gpt_NumberOfPartitionEntries;
22919 	gpe_lba = buffer->efi_gpt_PartitionEntryLBA;
22920 	if (p64.p_partno > nparts) {
22921 		/* couldn't find it */
22922 		rval = ESRCH;
22923 		goto done_error;
22924 	}
22925 	/*
22926 	 * if we're dealing with a partition that's out of the normal
22927 	 * 16K block, adjust accordingly
22928 	 */
22929 	gpe_lba += p64.p_partno / sizeof (efi_gpe_t);
22930 	rval = sd_send_scsi_READ(un, buffer, EFI_MIN_ARRAY_SIZE,
22931 			gpe_lba, SD_PATH_DIRECT);
22932 	if (rval) {
22933 		goto done_error;
22934 	}
22935 	partitions = (efi_gpe_t *)buffer;
22936 
22937 	sd_swap_efi_gpe(nparts, partitions);
22938 
22939 	partitions += p64.p_partno;
22940 	bcopy(&partitions->efi_gpe_PartitionTypeGUID, &p64.p_type,
22941 	    sizeof (struct uuid));
22942 	p64.p_start = partitions->efi_gpe_StartingLBA;
22943 	p64.p_size = partitions->efi_gpe_EndingLBA -
22944 			p64.p_start + 1;
22945 
22946 	if (ddi_copyout(&p64, (void *)arg, sizeof (struct partition64), flag))
22947 		rval = EFAULT;
22948 
22949 done_error:
22950 	kmem_free(buffer, EFI_MIN_ARRAY_SIZE);
22951 	return (rval);
22952 }
22953 
22954 
22955 /*
22956  *    Function: sd_dkio_set_vtoc
22957  *
22958  * Description: This routine is the driver entry point for handling user
22959  *		requests to set the current volume table of contents
22960  *		(DKIOCSVTOC).
22961  *
22962  *   Arguments: dev  - the device number
22963  *		arg  - pointer to user provided vtoc structure used to set the
22964  *			current vtoc.
22965  *		flag - this argument is a pass through to ddi_copyxxx()
22966  *		       directly from the mode argument of ioctl().
22967  *
22968  * Return Code: 0
22969  *		EFAULT
22970  *		ENXIO
22971  *		EINVAL
22972  *		ENOTSUP
22973  */
22974 
22975 static int
22976 sd_dkio_set_vtoc(dev_t dev, caddr_t arg, int flag)
22977 {
22978 	struct sd_lun	*un = NULL;
22979 	struct vtoc	user_vtoc;
22980 	int		rval = 0;
22981 
22982 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22983 		return (ENXIO);
22984 	}
22985 
22986 #if defined(__i386) || defined(__amd64)
22987 	if (un->un_tgt_blocksize != un->un_sys_blocksize) {
22988 		return (EINVAL);
22989 	}
22990 #endif
22991 
22992 #ifdef _MULTI_DATAMODEL
22993 	switch (ddi_model_convert_from(flag & FMODELS)) {
22994 	case DDI_MODEL_ILP32: {
22995 		struct vtoc32 user_vtoc32;
22996 
22997 		if (ddi_copyin((const void *)arg, &user_vtoc32,
22998 		    sizeof (struct vtoc32), flag)) {
22999 			return (EFAULT);
23000 		}
23001 		vtoc32tovtoc(user_vtoc32, user_vtoc);
23002 		break;
23003 	}
23004 
23005 	case DDI_MODEL_NONE:
23006 		if (ddi_copyin((const void *)arg, &user_vtoc,
23007 		    sizeof (struct vtoc), flag)) {
23008 			return (EFAULT);
23009 		}
23010 		break;
23011 	}
23012 #else /* ! _MULTI_DATAMODEL */
23013 	if (ddi_copyin((const void *)arg, &user_vtoc,
23014 	    sizeof (struct vtoc), flag)) {
23015 		return (EFAULT);
23016 	}
23017 #endif /* _MULTI_DATAMODEL */
23018 
23019 	mutex_enter(SD_MUTEX(un));
23020 	if (un->un_blockcount > DK_MAX_BLOCKS) {
23021 		mutex_exit(SD_MUTEX(un));
23022 		return (ENOTSUP);
23023 	}
23024 	if (un->un_g.dkg_ncyl == 0) {
23025 		mutex_exit(SD_MUTEX(un));
23026 		return (EINVAL);
23027 	}
23028 
23029 	mutex_exit(SD_MUTEX(un));
23030 	sd_clear_efi(un);
23031 	ddi_remove_minor_node(SD_DEVINFO(un), "wd");
23032 	ddi_remove_minor_node(SD_DEVINFO(un), "wd,raw");
23033 	(void) ddi_create_minor_node(SD_DEVINFO(un), "h",
23034 	    S_IFBLK, (SDUNIT(dev) << SDUNIT_SHIFT) | WD_NODE,
23035 	    un->un_node_type, NULL);
23036 	(void) ddi_create_minor_node(SD_DEVINFO(un), "h,raw",
23037 	    S_IFCHR, (SDUNIT(dev) << SDUNIT_SHIFT) | WD_NODE,
23038 	    un->un_node_type, NULL);
23039 	mutex_enter(SD_MUTEX(un));
23040 
23041 	if ((rval = sd_build_label_vtoc(un, &user_vtoc)) == 0) {
23042 		if ((rval = sd_write_label(dev)) == 0) {
23043 			if ((rval = sd_validate_geometry(un, SD_PATH_DIRECT))
23044 			    != 0) {
23045 				SD_ERROR(SD_LOG_IOCTL_DKIO, un,
23046 				    "sd_dkio_set_vtoc: "
23047 				    "Failed validate geometry\n");
23048 			}
23049 		}
23050 	}
23051 
23052 	/*
23053 	 * If sd_build_label_vtoc, or sd_write_label failed above write the
23054 	 * devid anyway, what can it hurt? Also preserve the device id by
23055 	 * writing to the disk acyl for the case where a devid has been
23056 	 * fabricated.
23057 	 */
23058 	if (un->un_f_devid_supported &&
23059 	    (un->un_f_opt_fab_devid == TRUE)) {
23060 		if (un->un_devid == NULL) {
23061 			sd_register_devid(un, SD_DEVINFO(un),
23062 			    SD_TARGET_IS_UNRESERVED);
23063 		} else {
23064 			/*
23065 			 * The device id for this disk has been
23066 			 * fabricated. Fabricated device id's are
23067 			 * managed by storing them in the last 2
23068 			 * available sectors on the drive. The device
23069 			 * id must be preserved by writing it back out
23070 			 * to this location.
23071 			 */
23072 			if (sd_write_deviceid(un) != 0) {
23073 				ddi_devid_free(un->un_devid);
23074 				un->un_devid = NULL;
23075 			}
23076 		}
23077 	}
23078 	mutex_exit(SD_MUTEX(un));
23079 	return (rval);
23080 }
23081 
23082 
23083 /*
23084  *    Function: sd_build_label_vtoc
23085  *
23086  * Description: This routine updates the driver soft state current volume table
23087  *		of contents based on a user specified vtoc.
23088  *
23089  *   Arguments: un - driver soft state (unit) structure
23090  *		user_vtoc - pointer to vtoc structure specifying vtoc to be used
23091  *			    to update the driver soft state.
23092  *
23093  * Return Code: 0
23094  *		EINVAL
23095  */
23096 
23097 static int
23098 sd_build_label_vtoc(struct sd_lun *un, struct vtoc *user_vtoc)
23099 {
23100 	struct dk_map		*lmap;
23101 	struct partition	*vpart;
23102 	int			nblks;
23103 #if defined(_SUNOS_VTOC_8)
23104 	int			ncyl;
23105 	struct dk_map2		*lpart;
23106 #endif	/* defined(_SUNOS_VTOC_8) */
23107 	int			i;
23108 
23109 	ASSERT(mutex_owned(SD_MUTEX(un)));
23110 
23111 	/* Sanity-check the vtoc */
23112 	if (user_vtoc->v_sanity != VTOC_SANE ||
23113 	    user_vtoc->v_sectorsz != un->un_sys_blocksize ||
23114 	    user_vtoc->v_nparts != V_NUMPAR) {
23115 		return (EINVAL);
23116 	}
23117 
23118 	nblks = un->un_g.dkg_nsect * un->un_g.dkg_nhead;
23119 	if (nblks == 0) {
23120 		return (EINVAL);
23121 	}
23122 
23123 #if defined(_SUNOS_VTOC_8)
23124 	vpart = user_vtoc->v_part;
23125 	for (i = 0; i < V_NUMPAR; i++) {
23126 		if ((vpart->p_start % nblks) != 0) {
23127 			return (EINVAL);
23128 		}
23129 		ncyl = vpart->p_start / nblks;
23130 		ncyl += vpart->p_size / nblks;
23131 		if ((vpart->p_size % nblks) != 0) {
23132 			ncyl++;
23133 		}
23134 		if (ncyl > (int)un->un_g.dkg_ncyl) {
23135 			return (EINVAL);
23136 		}
23137 		vpart++;
23138 	}
23139 #endif	/* defined(_SUNOS_VTOC_8) */
23140 
23141 	/* Put appropriate vtoc structure fields into the disk label */
23142 #if defined(_SUNOS_VTOC_16)
23143 	/*
23144 	 * The vtoc is always a 32bit data structure to maintain the
23145 	 * on-disk format. Convert "in place" instead of bcopying it.
23146 	 */
23147 	vtoctovtoc32((*user_vtoc), (*((struct vtoc32 *)&(un->un_vtoc))));
23148 
23149 	/*
23150 	 * in the 16-slice vtoc, starting sectors are expressed in
23151 	 * numbers *relative* to the start of the Solaris fdisk partition.
23152 	 */
23153 	lmap = un->un_map;
23154 	vpart = user_vtoc->v_part;
23155 
23156 	for (i = 0; i < (int)user_vtoc->v_nparts; i++, lmap++, vpart++) {
23157 		lmap->dkl_cylno = vpart->p_start / nblks;
23158 		lmap->dkl_nblk = vpart->p_size;
23159 	}
23160 
23161 #elif defined(_SUNOS_VTOC_8)
23162 
23163 	un->un_vtoc.v_bootinfo[0] = (uint32_t)user_vtoc->v_bootinfo[0];
23164 	un->un_vtoc.v_bootinfo[1] = (uint32_t)user_vtoc->v_bootinfo[1];
23165 	un->un_vtoc.v_bootinfo[2] = (uint32_t)user_vtoc->v_bootinfo[2];
23166 
23167 	un->un_vtoc.v_sanity = (uint32_t)user_vtoc->v_sanity;
23168 	un->un_vtoc.v_version = (uint32_t)user_vtoc->v_version;
23169 
23170 	bcopy(user_vtoc->v_volume, un->un_vtoc.v_volume, LEN_DKL_VVOL);
23171 
23172 	un->un_vtoc.v_nparts = user_vtoc->v_nparts;
23173 
23174 	bcopy(user_vtoc->v_reserved, un->un_vtoc.v_reserved,
23175 	    sizeof (un->un_vtoc.v_reserved));
23176 
23177 	/*
23178 	 * Note the conversion from starting sector number
23179 	 * to starting cylinder number.
23180 	 * Return error if division results in a remainder.
23181 	 */
23182 	lmap = un->un_map;
23183 	lpart = un->un_vtoc.v_part;
23184 	vpart = user_vtoc->v_part;
23185 
23186 	for (i = 0; i < (int)user_vtoc->v_nparts; i++) {
23187 		lpart->p_tag  = vpart->p_tag;
23188 		lpart->p_flag = vpart->p_flag;
23189 		lmap->dkl_cylno = vpart->p_start / nblks;
23190 		lmap->dkl_nblk = vpart->p_size;
23191 
23192 		lmap++;
23193 		lpart++;
23194 		vpart++;
23195 
23196 		/* (4387723) */
23197 #ifdef _LP64
23198 		if (user_vtoc->timestamp[i] > TIME32_MAX) {
23199 			un->un_vtoc.v_timestamp[i] = TIME32_MAX;
23200 		} else {
23201 			un->un_vtoc.v_timestamp[i] = user_vtoc->timestamp[i];
23202 		}
23203 #else
23204 		un->un_vtoc.v_timestamp[i] = user_vtoc->timestamp[i];
23205 #endif
23206 	}
23207 
23208 	bcopy(user_vtoc->v_asciilabel, un->un_asciilabel, LEN_DKL_ASCII);
23209 #else
23210 #error "No VTOC format defined."
23211 #endif
23212 	return (0);
23213 }
23214 
23215 /*
23216  *    Function: sd_clear_efi
23217  *
23218  * Description: This routine clears all EFI labels.
23219  *
23220  *   Arguments: un - driver soft state (unit) structure
23221  *
23222  * Return Code: void
23223  */
23224 
23225 static void
23226 sd_clear_efi(struct sd_lun *un)
23227 {
23228 	efi_gpt_t	*gpt;
23229 	uint_t		lbasize;
23230 	uint64_t	cap;
23231 	int rval;
23232 
23233 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23234 
23235 	gpt = kmem_alloc(sizeof (efi_gpt_t), KM_SLEEP);
23236 
23237 	if (sd_send_scsi_READ(un, gpt, DEV_BSIZE, 1, SD_PATH_DIRECT) != 0) {
23238 		goto done;
23239 	}
23240 
23241 	sd_swap_efi_gpt(gpt);
23242 	rval = sd_validate_efi(gpt);
23243 	if (rval == 0) {
23244 		/* clear primary */
23245 		bzero(gpt, sizeof (efi_gpt_t));
23246 		if ((rval = sd_send_scsi_WRITE(un, gpt, EFI_LABEL_SIZE, 1,
23247 			SD_PATH_DIRECT))) {
23248 			SD_INFO(SD_LOG_IO_PARTITION, un,
23249 				"sd_clear_efi: clear primary label failed\n");
23250 		}
23251 	}
23252 	/* the backup */
23253 	rval = sd_send_scsi_READ_CAPACITY(un, &cap, &lbasize,
23254 	    SD_PATH_DIRECT);
23255 	if (rval) {
23256 		goto done;
23257 	}
23258 	/*
23259 	 * The MMC standard allows READ CAPACITY to be
23260 	 * inaccurate by a bounded amount (in the interest of
23261 	 * response latency).  As a result, failed READs are
23262 	 * commonplace (due to the reading of metadata and not
23263 	 * data). Depending on the per-Vendor/drive Sense data,
23264 	 * the failed READ can cause many (unnecessary) retries.
23265 	 */
23266 	if ((rval = sd_send_scsi_READ(un, gpt, lbasize,
23267 	    cap - 1, ISCD(un) ? SD_PATH_DIRECT_PRIORITY :
23268 		SD_PATH_DIRECT)) != 0) {
23269 		goto done;
23270 	}
23271 	sd_swap_efi_gpt(gpt);
23272 	rval = sd_validate_efi(gpt);
23273 	if (rval == 0) {
23274 		/* clear backup */
23275 		SD_TRACE(SD_LOG_IOCTL, un, "sd_clear_efi clear backup@%lu\n",
23276 			cap-1);
23277 		bzero(gpt, sizeof (efi_gpt_t));
23278 		if ((rval = sd_send_scsi_WRITE(un, gpt, EFI_LABEL_SIZE,
23279 		    cap-1, SD_PATH_DIRECT))) {
23280 			SD_INFO(SD_LOG_IO_PARTITION, un,
23281 				"sd_clear_efi: clear backup label failed\n");
23282 		}
23283 	}
23284 
23285 done:
23286 	kmem_free(gpt, sizeof (efi_gpt_t));
23287 }
23288 
23289 /*
23290  *    Function: sd_set_vtoc
23291  *
23292  * Description: This routine writes data to the appropriate positions
23293  *
23294  *   Arguments: un - driver soft state (unit) structure
23295  *              dkl  - the data to be written
23296  *
23297  * Return: void
23298  */
23299 
23300 static int
23301 sd_set_vtoc(struct sd_lun *un, struct dk_label *dkl)
23302 {
23303 	void			*shadow_buf;
23304 	uint_t			label_addr;
23305 	int			sec;
23306 	int			blk;
23307 	int			head;
23308 	int			cyl;
23309 	int			rval;
23310 
23311 #if defined(__i386) || defined(__amd64)
23312 	label_addr = un->un_solaris_offset + DK_LABEL_LOC;
23313 #else
23314 	/* Write the primary label at block 0 of the solaris partition. */
23315 	label_addr = 0;
23316 #endif
23317 
23318 	if (NOT_DEVBSIZE(un)) {
23319 		shadow_buf = kmem_zalloc(un->un_tgt_blocksize, KM_SLEEP);
23320 		/*
23321 		 * Read the target's first block.
23322 		 */
23323 		if ((rval = sd_send_scsi_READ(un, shadow_buf,
23324 		    un->un_tgt_blocksize, label_addr,
23325 		    SD_PATH_STANDARD)) != 0) {
23326 			goto exit;
23327 		}
23328 		/*
23329 		 * Copy the contents of the label into the shadow buffer
23330 		 * which is of the size of target block size.
23331 		 */
23332 		bcopy(dkl, shadow_buf, sizeof (struct dk_label));
23333 	}
23334 
23335 	/* Write the primary label */
23336 	if (NOT_DEVBSIZE(un)) {
23337 		rval = sd_send_scsi_WRITE(un, shadow_buf, un->un_tgt_blocksize,
23338 		    label_addr, SD_PATH_STANDARD);
23339 	} else {
23340 		rval = sd_send_scsi_WRITE(un, dkl, un->un_sys_blocksize,
23341 		    label_addr, SD_PATH_STANDARD);
23342 	}
23343 	if (rval != 0) {
23344 		return (rval);
23345 	}
23346 
23347 	/*
23348 	 * Calculate where the backup labels go.  They are always on
23349 	 * the last alternate cylinder, but some older drives put them
23350 	 * on head 2 instead of the last head.	They are always on the
23351 	 * first 5 odd sectors of the appropriate track.
23352 	 *
23353 	 * We have no choice at this point, but to believe that the
23354 	 * disk label is valid.	 Use the geometry of the disk
23355 	 * as described in the label.
23356 	 */
23357 	cyl  = dkl->dkl_ncyl  + dkl->dkl_acyl - 1;
23358 	head = dkl->dkl_nhead - 1;
23359 
23360 	/*
23361 	 * Write and verify the backup labels. Make sure we don't try to
23362 	 * write past the last cylinder.
23363 	 */
23364 	for (sec = 1; ((sec < 5 * 2 + 1) && (sec < dkl->dkl_nsect)); sec += 2) {
23365 		blk = (daddr_t)(
23366 		    (cyl * ((dkl->dkl_nhead * dkl->dkl_nsect) - dkl->dkl_apc)) +
23367 		    (head * dkl->dkl_nsect) + sec);
23368 #if defined(__i386) || defined(__amd64)
23369 		blk += un->un_solaris_offset;
23370 #endif
23371 		if (NOT_DEVBSIZE(un)) {
23372 			uint64_t	tblk;
23373 			/*
23374 			 * Need to read the block first for read modify write.
23375 			 */
23376 			tblk = (uint64_t)blk;
23377 			blk = (int)((tblk * un->un_sys_blocksize) /
23378 			    un->un_tgt_blocksize);
23379 			if ((rval = sd_send_scsi_READ(un, shadow_buf,
23380 			    un->un_tgt_blocksize, blk,
23381 			    SD_PATH_STANDARD)) != 0) {
23382 				goto exit;
23383 			}
23384 			/*
23385 			 * Modify the shadow buffer with the label.
23386 			 */
23387 			bcopy(dkl, shadow_buf, sizeof (struct dk_label));
23388 			rval = sd_send_scsi_WRITE(un, shadow_buf,
23389 			    un->un_tgt_blocksize, blk, SD_PATH_STANDARD);
23390 		} else {
23391 			rval = sd_send_scsi_WRITE(un, dkl, un->un_sys_blocksize,
23392 			    blk, SD_PATH_STANDARD);
23393 			SD_INFO(SD_LOG_IO_PARTITION, un,
23394 			"sd_set_vtoc: wrote backup label %d\n", blk);
23395 		}
23396 		if (rval != 0) {
23397 			goto exit;
23398 		}
23399 	}
23400 exit:
23401 	if (NOT_DEVBSIZE(un)) {
23402 		kmem_free(shadow_buf, un->un_tgt_blocksize);
23403 	}
23404 	return (rval);
23405 }
23406 
23407 /*
23408  *    Function: sd_clear_vtoc
23409  *
23410  * Description: This routine clears out the VTOC labels.
23411  *
23412  *   Arguments: un - driver soft state (unit) structure
23413  *
23414  * Return: void
23415  */
23416 
23417 static void
23418 sd_clear_vtoc(struct sd_lun *un)
23419 {
23420 	struct dk_label		*dkl;
23421 
23422 	mutex_exit(SD_MUTEX(un));
23423 	dkl = kmem_zalloc(sizeof (struct dk_label), KM_SLEEP);
23424 	mutex_enter(SD_MUTEX(un));
23425 	/*
23426 	 * sd_set_vtoc uses these fields in order to figure out
23427 	 * where to overwrite the backup labels
23428 	 */
23429 	dkl->dkl_apc    = un->un_g.dkg_apc;
23430 	dkl->dkl_ncyl   = un->un_g.dkg_ncyl;
23431 	dkl->dkl_acyl   = un->un_g.dkg_acyl;
23432 	dkl->dkl_nhead  = un->un_g.dkg_nhead;
23433 	dkl->dkl_nsect  = un->un_g.dkg_nsect;
23434 	mutex_exit(SD_MUTEX(un));
23435 	(void) sd_set_vtoc(un, dkl);
23436 	kmem_free(dkl, sizeof (struct dk_label));
23437 
23438 	mutex_enter(SD_MUTEX(un));
23439 }
23440 
23441 /*
23442  *    Function: sd_write_label
23443  *
23444  * Description: This routine will validate and write the driver soft state vtoc
23445  *		contents to the device.
23446  *
23447  *   Arguments: dev - the device number
23448  *
23449  * Return Code: the code returned by sd_send_scsi_cmd()
23450  *		0
23451  *		EINVAL
23452  *		ENXIO
23453  *		ENOMEM
23454  */
23455 
23456 static int
23457 sd_write_label(dev_t dev)
23458 {
23459 	struct sd_lun		*un;
23460 	struct dk_label		*dkl;
23461 	short			sum;
23462 	short			*sp;
23463 	int			i;
23464 	int			rval;
23465 
23466 	if (((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) ||
23467 	    (un->un_state == SD_STATE_OFFLINE)) {
23468 		return (ENXIO);
23469 	}
23470 	ASSERT(mutex_owned(SD_MUTEX(un)));
23471 	mutex_exit(SD_MUTEX(un));
23472 	dkl = kmem_zalloc(sizeof (struct dk_label), KM_SLEEP);
23473 	mutex_enter(SD_MUTEX(un));
23474 
23475 	bcopy(&un->un_vtoc, &dkl->dkl_vtoc, sizeof (struct dk_vtoc));
23476 	dkl->dkl_rpm	= un->un_g.dkg_rpm;
23477 	dkl->dkl_pcyl	= un->un_g.dkg_pcyl;
23478 	dkl->dkl_apc	= un->un_g.dkg_apc;
23479 	dkl->dkl_intrlv = un->un_g.dkg_intrlv;
23480 	dkl->dkl_ncyl	= un->un_g.dkg_ncyl;
23481 	dkl->dkl_acyl	= un->un_g.dkg_acyl;
23482 	dkl->dkl_nhead	= un->un_g.dkg_nhead;
23483 	dkl->dkl_nsect	= un->un_g.dkg_nsect;
23484 
23485 #if defined(_SUNOS_VTOC_8)
23486 	dkl->dkl_obs1	= un->un_g.dkg_obs1;
23487 	dkl->dkl_obs2	= un->un_g.dkg_obs2;
23488 	dkl->dkl_obs3	= un->un_g.dkg_obs3;
23489 	for (i = 0; i < NDKMAP; i++) {
23490 		dkl->dkl_map[i].dkl_cylno = un->un_map[i].dkl_cylno;
23491 		dkl->dkl_map[i].dkl_nblk  = un->un_map[i].dkl_nblk;
23492 	}
23493 	bcopy(un->un_asciilabel, dkl->dkl_asciilabel, LEN_DKL_ASCII);
23494 #elif defined(_SUNOS_VTOC_16)
23495 	dkl->dkl_skew	= un->un_dkg_skew;
23496 #else
23497 #error "No VTOC format defined."
23498 #endif
23499 
23500 	dkl->dkl_magic			= DKL_MAGIC;
23501 	dkl->dkl_write_reinstruct	= un->un_g.dkg_write_reinstruct;
23502 	dkl->dkl_read_reinstruct	= un->un_g.dkg_read_reinstruct;
23503 
23504 	/* Construct checksum for the new disk label */
23505 	sum = 0;
23506 	sp = (short *)dkl;
23507 	i = sizeof (struct dk_label) / sizeof (short);
23508 	while (i--) {
23509 		sum ^= *sp++;
23510 	}
23511 	dkl->dkl_cksum = sum;
23512 
23513 	mutex_exit(SD_MUTEX(un));
23514 
23515 	rval = sd_set_vtoc(un, dkl);
23516 exit:
23517 	kmem_free(dkl, sizeof (struct dk_label));
23518 	mutex_enter(SD_MUTEX(un));
23519 	return (rval);
23520 }
23521 
23522 static int
23523 sd_dkio_set_efi(dev_t dev, caddr_t arg, int flag)
23524 {
23525 	struct sd_lun	*un = NULL;
23526 	dk_efi_t	user_efi;
23527 	int		rval = 0;
23528 	void		*buffer;
23529 
23530 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL)
23531 		return (ENXIO);
23532 
23533 	if (ddi_copyin(arg, &user_efi, sizeof (dk_efi_t), flag))
23534 		return (EFAULT);
23535 
23536 	user_efi.dki_data = (void *)(uintptr_t)user_efi.dki_data_64;
23537 
23538 	if ((user_efi.dki_length % un->un_tgt_blocksize) ||
23539 	    (user_efi.dki_length > un->un_max_xfer_size))
23540 		return (EINVAL);
23541 
23542 	buffer = kmem_alloc(user_efi.dki_length, KM_SLEEP);
23543 	if (ddi_copyin(user_efi.dki_data, buffer, user_efi.dki_length, flag)) {
23544 		rval = EFAULT;
23545 	} else {
23546 		/*
23547 		 * let's clear the vtoc labels and clear the softstate
23548 		 * vtoc.
23549 		 */
23550 		mutex_enter(SD_MUTEX(un));
23551 		if (un->un_vtoc.v_sanity == VTOC_SANE) {
23552 			SD_TRACE(SD_LOG_IO_PARTITION, un,
23553 				"sd_dkio_set_efi: CLEAR VTOC\n");
23554 			sd_clear_vtoc(un);
23555 			bzero(&un->un_vtoc, sizeof (struct dk_vtoc));
23556 			mutex_exit(SD_MUTEX(un));
23557 			ddi_remove_minor_node(SD_DEVINFO(un), "h");
23558 			ddi_remove_minor_node(SD_DEVINFO(un), "h,raw");
23559 			(void) ddi_create_minor_node(SD_DEVINFO(un), "wd",
23560 			    S_IFBLK,
23561 			    (SDUNIT(dev) << SDUNIT_SHIFT) | WD_NODE,
23562 			    un->un_node_type, NULL);
23563 			(void) ddi_create_minor_node(SD_DEVINFO(un), "wd,raw",
23564 			    S_IFCHR,
23565 			    (SDUNIT(dev) << SDUNIT_SHIFT) | WD_NODE,
23566 			    un->un_node_type, NULL);
23567 		} else
23568 			mutex_exit(SD_MUTEX(un));
23569 		rval = sd_send_scsi_WRITE(un, buffer, user_efi.dki_length,
23570 		    user_efi.dki_lba, SD_PATH_DIRECT);
23571 		if (rval == 0) {
23572 			mutex_enter(SD_MUTEX(un));
23573 			un->un_f_geometry_is_valid = FALSE;
23574 			mutex_exit(SD_MUTEX(un));
23575 		}
23576 	}
23577 	kmem_free(buffer, user_efi.dki_length);
23578 	return (rval);
23579 }
23580 
23581 /*
23582  *    Function: sd_dkio_get_mboot
23583  *
23584  * Description: This routine is the driver entry point for handling user
23585  *		requests to get the current device mboot (DKIOCGMBOOT)
23586  *
23587  *   Arguments: dev  - the device number
23588  *		arg  - pointer to user provided mboot structure specifying
23589  *			the current mboot.
23590  *		flag - this argument is a pass through to ddi_copyxxx()
23591  *		       directly from the mode argument of ioctl().
23592  *
23593  * Return Code: 0
23594  *		EINVAL
23595  *		EFAULT
23596  *		ENXIO
23597  */
23598 
23599 static int
23600 sd_dkio_get_mboot(dev_t dev, caddr_t arg, int flag)
23601 {
23602 	struct sd_lun	*un;
23603 	struct mboot	*mboot;
23604 	int		rval;
23605 	size_t		buffer_size;
23606 
23607 	if (((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) ||
23608 	    (un->un_state == SD_STATE_OFFLINE)) {
23609 		return (ENXIO);
23610 	}
23611 
23612 	if (!un->un_f_mboot_supported || arg == NULL) {
23613 		return (EINVAL);
23614 	}
23615 
23616 	/*
23617 	 * Read the mboot block, located at absolute block 0 on the target.
23618 	 */
23619 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct mboot));
23620 
23621 	SD_TRACE(SD_LOG_IO_PARTITION, un,
23622 	    "sd_dkio_get_mboot: allocation size: 0x%x\n", buffer_size);
23623 
23624 	mboot = kmem_zalloc(buffer_size, KM_SLEEP);
23625 	if ((rval = sd_send_scsi_READ(un, mboot, buffer_size, 0,
23626 	    SD_PATH_STANDARD)) == 0) {
23627 		if (ddi_copyout(mboot, (void *)arg,
23628 		    sizeof (struct mboot), flag) != 0) {
23629 			rval = EFAULT;
23630 		}
23631 	}
23632 	kmem_free(mboot, buffer_size);
23633 	return (rval);
23634 }
23635 
23636 
23637 /*
23638  *    Function: sd_dkio_set_mboot
23639  *
23640  * Description: This routine is the driver entry point for handling user
23641  *		requests to validate and set the device master boot
23642  *		(DKIOCSMBOOT).
23643  *
23644  *   Arguments: dev  - the device number
23645  *		arg  - pointer to user provided mboot structure used to set the
23646  *			master boot.
23647  *		flag - this argument is a pass through to ddi_copyxxx()
23648  *		       directly from the mode argument of ioctl().
23649  *
23650  * Return Code: 0
23651  *		EINVAL
23652  *		EFAULT
23653  *		ENXIO
23654  */
23655 
23656 static int
23657 sd_dkio_set_mboot(dev_t dev, caddr_t arg, int flag)
23658 {
23659 	struct sd_lun	*un = NULL;
23660 	struct mboot	*mboot = NULL;
23661 	int		rval;
23662 	ushort_t	magic;
23663 
23664 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23665 		return (ENXIO);
23666 	}
23667 
23668 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23669 
23670 	if (!un->un_f_mboot_supported) {
23671 		return (EINVAL);
23672 	}
23673 
23674 	if (arg == NULL) {
23675 		return (EINVAL);
23676 	}
23677 
23678 	mboot = kmem_zalloc(sizeof (struct mboot), KM_SLEEP);
23679 
23680 	if (ddi_copyin((const void *)arg, mboot,
23681 	    sizeof (struct mboot), flag) != 0) {
23682 		kmem_free(mboot, (size_t)(sizeof (struct mboot)));
23683 		return (EFAULT);
23684 	}
23685 
23686 	/* Is this really a master boot record? */
23687 	magic = LE_16(mboot->signature);
23688 	if (magic != MBB_MAGIC) {
23689 		kmem_free(mboot, (size_t)(sizeof (struct mboot)));
23690 		return (EINVAL);
23691 	}
23692 
23693 	rval = sd_send_scsi_WRITE(un, mboot, un->un_sys_blocksize, 0,
23694 	    SD_PATH_STANDARD);
23695 
23696 	mutex_enter(SD_MUTEX(un));
23697 #if defined(__i386) || defined(__amd64)
23698 	if (rval == 0) {
23699 		/*
23700 		 * mboot has been written successfully.
23701 		 * update the fdisk and vtoc tables in memory
23702 		 */
23703 		rval = sd_update_fdisk_and_vtoc(un);
23704 		if ((un->un_f_geometry_is_valid == FALSE) || (rval != 0)) {
23705 			mutex_exit(SD_MUTEX(un));
23706 			kmem_free(mboot, (size_t)(sizeof (struct mboot)));
23707 			return (rval);
23708 		}
23709 	}
23710 
23711 	/*
23712 	 * If the mboot write fails, write the devid anyway, what can it hurt?
23713 	 * Also preserve the device id by writing to the disk acyl for the case
23714 	 * where a devid has been fabricated.
23715 	 */
23716 	if (un->un_f_devid_supported && un->un_f_opt_fab_devid) {
23717 		if (un->un_devid == NULL) {
23718 			sd_register_devid(un, SD_DEVINFO(un),
23719 			    SD_TARGET_IS_UNRESERVED);
23720 		} else {
23721 			/*
23722 			 * The device id for this disk has been
23723 			 * fabricated. Fabricated device id's are
23724 			 * managed by storing them in the last 2
23725 			 * available sectors on the drive. The device
23726 			 * id must be preserved by writing it back out
23727 			 * to this location.
23728 			 */
23729 			if (sd_write_deviceid(un) != 0) {
23730 				ddi_devid_free(un->un_devid);
23731 				un->un_devid = NULL;
23732 			}
23733 		}
23734 	}
23735 
23736 #ifdef __lock_lint
23737 	sd_setup_default_geometry(un);
23738 #endif
23739 
23740 #else
23741 	if (rval == 0) {
23742 		/*
23743 		 * mboot has been written successfully.
23744 		 * set up the default geometry and VTOC
23745 		 */
23746 		if (un->un_blockcount <= DK_MAX_BLOCKS)
23747 			sd_setup_default_geometry(un);
23748 	}
23749 #endif
23750 	mutex_exit(SD_MUTEX(un));
23751 	kmem_free(mboot, (size_t)(sizeof (struct mboot)));
23752 	return (rval);
23753 }
23754 
23755 
23756 /*
23757  *    Function: sd_setup_default_geometry
23758  *
23759  * Description: This local utility routine sets the default geometry as part of
23760  *		setting the device mboot.
23761  *
23762  *   Arguments: un - driver soft state (unit) structure
23763  *
23764  * Note: This may be redundant with sd_build_default_label.
23765  */
23766 
23767 static void
23768 sd_setup_default_geometry(struct sd_lun *un)
23769 {
23770 	/* zero out the soft state geometry and partition table. */
23771 	bzero(&un->un_g, sizeof (struct dk_geom));
23772 	bzero(&un->un_vtoc, sizeof (struct dk_vtoc));
23773 	bzero(un->un_map, NDKMAP * (sizeof (struct dk_map)));
23774 	un->un_asciilabel[0] = '\0';
23775 
23776 	/*
23777 	 * For the rpm, we use the minimum for the disk.
23778 	 * For the head, cyl and number of sector per track,
23779 	 * if the capacity <= 1GB, head = 64, sect = 32.
23780 	 * else head = 255, sect 63
23781 	 * Note: the capacity should be equal to C*H*S values.
23782 	 * This will cause some truncation of size due to
23783 	 * round off errors. For CD-ROMs, this truncation can
23784 	 * have adverse side effects, so returning ncyl and
23785 	 * nhead as 1. The nsect will overflow for most of
23786 	 * CD-ROMs as nsect is of type ushort.
23787 	 */
23788 	if (ISCD(un)) {
23789 		un->un_g.dkg_ncyl = 1;
23790 		un->un_g.dkg_nhead = 1;
23791 		un->un_g.dkg_nsect = un->un_blockcount;
23792 	} else {
23793 		if (un->un_blockcount <= 0x1000) {
23794 			/* Needed for unlabeled SCSI floppies. */
23795 			un->un_g.dkg_nhead = 2;
23796 			un->un_g.dkg_ncyl = 80;
23797 			un->un_g.dkg_pcyl = 80;
23798 			un->un_g.dkg_nsect = un->un_blockcount / (2 * 80);
23799 		} else if (un->un_blockcount <= 0x200000) {
23800 			un->un_g.dkg_nhead = 64;
23801 			un->un_g.dkg_nsect = 32;
23802 			un->un_g.dkg_ncyl = un->un_blockcount / (64 * 32);
23803 		} else {
23804 			un->un_g.dkg_nhead = 255;
23805 			un->un_g.dkg_nsect = 63;
23806 			un->un_g.dkg_ncyl = un->un_blockcount / (255 * 63);
23807 		}
23808 		un->un_blockcount = un->un_g.dkg_ncyl *
23809 		    un->un_g.dkg_nhead * un->un_g.dkg_nsect;
23810 	}
23811 	un->un_g.dkg_acyl = 0;
23812 	un->un_g.dkg_bcyl = 0;
23813 	un->un_g.dkg_intrlv = 1;
23814 	un->un_g.dkg_rpm = 200;
23815 	un->un_g.dkg_read_reinstruct = 0;
23816 	un->un_g.dkg_write_reinstruct = 0;
23817 	if (un->un_g.dkg_pcyl == 0) {
23818 		un->un_g.dkg_pcyl = un->un_g.dkg_ncyl + un->un_g.dkg_acyl;
23819 	}
23820 
23821 	un->un_map['a'-'a'].dkl_cylno = 0;
23822 	un->un_map['a'-'a'].dkl_nblk = un->un_blockcount;
23823 	un->un_map['c'-'a'].dkl_cylno = 0;
23824 	un->un_map['c'-'a'].dkl_nblk = un->un_blockcount;
23825 	un->un_f_geometry_is_valid = FALSE;
23826 }
23827 
23828 
23829 #if defined(__i386) || defined(__amd64)
23830 /*
23831  *    Function: sd_update_fdisk_and_vtoc
23832  *
23833  * Description: This local utility routine updates the device fdisk and vtoc
23834  *		as part of setting the device mboot.
23835  *
23836  *   Arguments: un - driver soft state (unit) structure
23837  *
23838  * Return Code: 0 for success or errno-type return code.
23839  *
23840  *    Note:x86: This looks like a duplicate of sd_validate_geometry(), but
23841  *		these did exist seperately in x86 sd.c!!!
23842  */
23843 
23844 static int
23845 sd_update_fdisk_and_vtoc(struct sd_lun *un)
23846 {
23847 	static char	labelstring[128];
23848 	static char	buf[256];
23849 	char		*label = 0;
23850 	int		count;
23851 	int		label_rc = 0;
23852 	int		gvalid = un->un_f_geometry_is_valid;
23853 	int		fdisk_rval;
23854 	int		lbasize;
23855 	int		capacity;
23856 
23857 	ASSERT(mutex_owned(SD_MUTEX(un)));
23858 
23859 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
23860 		return (EINVAL);
23861 	}
23862 
23863 	if (un->un_f_blockcount_is_valid == FALSE) {
23864 		return (EINVAL);
23865 	}
23866 
23867 #if defined(_SUNOS_VTOC_16)
23868 	/*
23869 	 * Set up the "whole disk" fdisk partition; this should always
23870 	 * exist, regardless of whether the disk contains an fdisk table
23871 	 * or vtoc.
23872 	 */
23873 	un->un_map[P0_RAW_DISK].dkl_cylno = 0;
23874 	un->un_map[P0_RAW_DISK].dkl_nblk = un->un_blockcount;
23875 #endif	/* defined(_SUNOS_VTOC_16) */
23876 
23877 	/*
23878 	 * copy the lbasize and capacity so that if they're
23879 	 * reset while we're not holding the SD_MUTEX(un), we will
23880 	 * continue to use valid values after the SD_MUTEX(un) is
23881 	 * reacquired.
23882 	 */
23883 	lbasize  = un->un_tgt_blocksize;
23884 	capacity = un->un_blockcount;
23885 
23886 	/*
23887 	 * refresh the logical and physical geometry caches.
23888 	 * (data from mode sense format/rigid disk geometry pages,
23889 	 * and scsi_ifgetcap("geometry").
23890 	 */
23891 	sd_resync_geom_caches(un, capacity, lbasize, SD_PATH_DIRECT);
23892 
23893 	/*
23894 	 * Only DIRECT ACCESS devices will have Sun labels.
23895 	 * CD's supposedly have a Sun label, too
23896 	 */
23897 	if (un->un_f_vtoc_label_supported) {
23898 		fdisk_rval = sd_read_fdisk(un, capacity, lbasize,
23899 		    SD_PATH_DIRECT);
23900 		if (fdisk_rval == SD_CMD_FAILURE) {
23901 			ASSERT(mutex_owned(SD_MUTEX(un)));
23902 			return (EIO);
23903 		}
23904 
23905 		if (fdisk_rval == SD_CMD_RESERVATION_CONFLICT) {
23906 			ASSERT(mutex_owned(SD_MUTEX(un)));
23907 			return (EACCES);
23908 		}
23909 
23910 		if (un->un_solaris_size <= DK_LABEL_LOC) {
23911 			/*
23912 			 * Found fdisk table but no Solaris partition entry,
23913 			 * so don't call sd_uselabel() and don't create
23914 			 * a default label.
23915 			 */
23916 			label_rc = 0;
23917 			un->un_f_geometry_is_valid = TRUE;
23918 			goto no_solaris_partition;
23919 		}
23920 
23921 #if defined(_SUNOS_VTOC_8)
23922 		label = (char *)un->un_asciilabel;
23923 #elif defined(_SUNOS_VTOC_16)
23924 		label = (char *)un->un_vtoc.v_asciilabel;
23925 #else
23926 #error "No VTOC format defined."
23927 #endif
23928 	} else if (capacity < 0) {
23929 		ASSERT(mutex_owned(SD_MUTEX(un)));
23930 		return (EINVAL);
23931 	}
23932 
23933 	/*
23934 	 * For Removable media We reach here if we have found a
23935 	 * SOLARIS PARTITION.
23936 	 * If un_f_geometry_is_valid is FALSE it indicates that the SOLARIS
23937 	 * PARTITION has changed from the previous one, hence we will setup a
23938 	 * default VTOC in this case.
23939 	 */
23940 	if (un->un_f_geometry_is_valid == FALSE) {
23941 		sd_build_default_label(un);
23942 		label_rc = 0;
23943 	}
23944 
23945 no_solaris_partition:
23946 	if ((!un->un_f_has_removable_media ||
23947 	    (un->un_f_has_removable_media &&
23948 	    un->un_mediastate == DKIO_EJECTED)) &&
23949 		(un->un_state == SD_STATE_NORMAL && !gvalid)) {
23950 		/*
23951 		 * Print out a message indicating who and what we are.
23952 		 * We do this only when we happen to really validate the
23953 		 * geometry. We may call sd_validate_geometry() at other
23954 		 * times, ioctl()'s like Get VTOC in which case we
23955 		 * don't want to print the label.
23956 		 * If the geometry is valid, print the label string,
23957 		 * else print vendor and product info, if available
23958 		 */
23959 		if ((un->un_f_geometry_is_valid == TRUE) && (label != NULL)) {
23960 			SD_INFO(SD_LOG_IOCTL_DKIO, un, "?<%s>\n", label);
23961 		} else {
23962 			mutex_enter(&sd_label_mutex);
23963 			sd_inq_fill(SD_INQUIRY(un)->inq_vid, VIDMAX,
23964 			    labelstring);
23965 			sd_inq_fill(SD_INQUIRY(un)->inq_pid, PIDMAX,
23966 			    &labelstring[64]);
23967 			(void) sprintf(buf, "?Vendor '%s', product '%s'",
23968 			    labelstring, &labelstring[64]);
23969 			if (un->un_f_blockcount_is_valid == TRUE) {
23970 				(void) sprintf(&buf[strlen(buf)],
23971 				    ", %" PRIu64 " %u byte blocks\n",
23972 				    un->un_blockcount,
23973 				    un->un_tgt_blocksize);
23974 			} else {
23975 				(void) sprintf(&buf[strlen(buf)],
23976 				    ", (unknown capacity)\n");
23977 			}
23978 			SD_INFO(SD_LOG_IOCTL_DKIO, un, buf);
23979 			mutex_exit(&sd_label_mutex);
23980 		}
23981 	}
23982 
23983 #if defined(_SUNOS_VTOC_16)
23984 	/*
23985 	 * If we have valid geometry, set up the remaining fdisk partitions.
23986 	 * Note that dkl_cylno is not used for the fdisk map entries, so
23987 	 * we set it to an entirely bogus value.
23988 	 */
23989 	for (count = 0; count < FD_NUMPART; count++) {
23990 		un->un_map[FDISK_P1 + count].dkl_cylno = -1;
23991 		un->un_map[FDISK_P1 + count].dkl_nblk =
23992 		    un->un_fmap[count].fmap_nblk;
23993 		un->un_offset[FDISK_P1 + count] =
23994 		    un->un_fmap[count].fmap_start;
23995 	}
23996 #endif
23997 
23998 	for (count = 0; count < NDKMAP; count++) {
23999 #if defined(_SUNOS_VTOC_8)
24000 		struct dk_map *lp  = &un->un_map[count];
24001 		un->un_offset[count] =
24002 		    un->un_g.dkg_nhead * un->un_g.dkg_nsect * lp->dkl_cylno;
24003 #elif defined(_SUNOS_VTOC_16)
24004 		struct dkl_partition *vp = &un->un_vtoc.v_part[count];
24005 		un->un_offset[count] = vp->p_start + un->un_solaris_offset;
24006 #else
24007 #error "No VTOC format defined."
24008 #endif
24009 	}
24010 
24011 	ASSERT(mutex_owned(SD_MUTEX(un)));
24012 	return (label_rc);
24013 }
24014 #endif
24015 
24016 
24017 /*
24018  *    Function: sd_check_media
24019  *
24020  * Description: This utility routine implements the functionality for the
24021  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
24022  *		driver state changes from that specified by the user
24023  *		(inserted or ejected). For example, if the user specifies
24024  *		DKIO_EJECTED and the current media state is inserted this
24025  *		routine will immediately return DKIO_INSERTED. However, if the
24026  *		current media state is not inserted the user thread will be
24027  *		blocked until the drive state changes. If DKIO_NONE is specified
24028  *		the user thread will block until a drive state change occurs.
24029  *
24030  *   Arguments: dev  - the device number
24031  *		state  - user pointer to a dkio_state, updated with the current
24032  *			drive state at return.
24033  *
24034  * Return Code: ENXIO
24035  *		EIO
24036  *		EAGAIN
24037  *		EINTR
24038  */
24039 
24040 static int
24041 sd_check_media(dev_t dev, enum dkio_state state)
24042 {
24043 	struct sd_lun		*un = NULL;
24044 	enum dkio_state		prev_state;
24045 	opaque_t		token = NULL;
24046 	int			rval = 0;
24047 
24048 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24049 		return (ENXIO);
24050 	}
24051 
24052 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
24053 
24054 	mutex_enter(SD_MUTEX(un));
24055 
24056 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
24057 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
24058 
24059 	prev_state = un->un_mediastate;
24060 
24061 	/* is there anything to do? */
24062 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
24063 		/*
24064 		 * submit the request to the scsi_watch service;
24065 		 * scsi_media_watch_cb() does the real work
24066 		 */
24067 		mutex_exit(SD_MUTEX(un));
24068 
24069 		/*
24070 		 * This change handles the case where a scsi watch request is
24071 		 * added to a device that is powered down. To accomplish this
24072 		 * we power up the device before adding the scsi watch request,
24073 		 * since the scsi watch sends a TUR directly to the device
24074 		 * which the device cannot handle if it is powered down.
24075 		 */
24076 		if (sd_pm_entry(un) != DDI_SUCCESS) {
24077 			mutex_enter(SD_MUTEX(un));
24078 			goto done;
24079 		}
24080 
24081 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
24082 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
24083 		    (caddr_t)dev);
24084 
24085 		sd_pm_exit(un);
24086 
24087 		mutex_enter(SD_MUTEX(un));
24088 		if (token == NULL) {
24089 			rval = EAGAIN;
24090 			goto done;
24091 		}
24092 
24093 		/*
24094 		 * This is a special case IOCTL that doesn't return
24095 		 * until the media state changes. Routine sdpower
24096 		 * knows about and handles this so don't count it
24097 		 * as an active cmd in the driver, which would
24098 		 * keep the device busy to the pm framework.
24099 		 * If the count isn't decremented the device can't
24100 		 * be powered down.
24101 		 */
24102 		un->un_ncmds_in_driver--;
24103 		ASSERT(un->un_ncmds_in_driver >= 0);
24104 
24105 		/*
24106 		 * if a prior request had been made, this will be the same
24107 		 * token, as scsi_watch was designed that way.
24108 		 */
24109 		un->un_swr_token = token;
24110 		un->un_specified_mediastate = state;
24111 
24112 		/*
24113 		 * now wait for media change
24114 		 * we will not be signalled unless mediastate == state but it is
24115 		 * still better to test for this condition, since there is a
24116 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
24117 		 */
24118 		SD_TRACE(SD_LOG_COMMON, un,
24119 		    "sd_check_media: waiting for media state change\n");
24120 		while (un->un_mediastate == state) {
24121 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
24122 				SD_TRACE(SD_LOG_COMMON, un,
24123 				    "sd_check_media: waiting for media state "
24124 				    "was interrupted\n");
24125 				un->un_ncmds_in_driver++;
24126 				rval = EINTR;
24127 				goto done;
24128 			}
24129 			SD_TRACE(SD_LOG_COMMON, un,
24130 			    "sd_check_media: received signal, state=%x\n",
24131 			    un->un_mediastate);
24132 		}
24133 		/*
24134 		 * Inc the counter to indicate the device once again
24135 		 * has an active outstanding cmd.
24136 		 */
24137 		un->un_ncmds_in_driver++;
24138 	}
24139 
24140 	/* invalidate geometry */
24141 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
24142 		sr_ejected(un);
24143 	}
24144 
24145 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
24146 		uint64_t	capacity;
24147 		uint_t		lbasize;
24148 
24149 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
24150 		mutex_exit(SD_MUTEX(un));
24151 		/*
24152 		 * Since the following routines use SD_PATH_DIRECT, we must
24153 		 * call PM directly before the upcoming disk accesses. This
24154 		 * may cause the disk to be power/spin up.
24155 		 */
24156 
24157 		if (sd_pm_entry(un) == DDI_SUCCESS) {
24158 			rval = sd_send_scsi_READ_CAPACITY(un,
24159 			    &capacity,
24160 			    &lbasize, SD_PATH_DIRECT);
24161 			if (rval != 0) {
24162 				sd_pm_exit(un);
24163 				mutex_enter(SD_MUTEX(un));
24164 				goto done;
24165 			}
24166 		} else {
24167 			rval = EIO;
24168 			mutex_enter(SD_MUTEX(un));
24169 			goto done;
24170 		}
24171 		mutex_enter(SD_MUTEX(un));
24172 
24173 		sd_update_block_info(un, lbasize, capacity);
24174 
24175 		un->un_f_geometry_is_valid	= FALSE;
24176 		(void) sd_validate_geometry(un, SD_PATH_DIRECT);
24177 
24178 		mutex_exit(SD_MUTEX(un));
24179 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
24180 		    SD_PATH_DIRECT);
24181 		sd_pm_exit(un);
24182 
24183 		mutex_enter(SD_MUTEX(un));
24184 	}
24185 done:
24186 	un->un_f_watcht_stopped = FALSE;
24187 	if (un->un_swr_token) {
24188 		/*
24189 		 * Use of this local token and the mutex ensures that we avoid
24190 		 * some race conditions associated with terminating the
24191 		 * scsi watch.
24192 		 */
24193 		token = un->un_swr_token;
24194 		un->un_swr_token = (opaque_t)NULL;
24195 		mutex_exit(SD_MUTEX(un));
24196 		(void) scsi_watch_request_terminate(token,
24197 		    SCSI_WATCH_TERMINATE_WAIT);
24198 		mutex_enter(SD_MUTEX(un));
24199 	}
24200 
24201 	/*
24202 	 * Update the capacity kstat value, if no media previously
24203 	 * (capacity kstat is 0) and a media has been inserted
24204 	 * (un_f_blockcount_is_valid == TRUE)
24205 	 */
24206 	if (un->un_errstats) {
24207 		struct sd_errstats	*stp = NULL;
24208 
24209 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
24210 		if ((stp->sd_capacity.value.ui64 == 0) &&
24211 		    (un->un_f_blockcount_is_valid == TRUE)) {
24212 			stp->sd_capacity.value.ui64 =
24213 			    (uint64_t)((uint64_t)un->un_blockcount *
24214 			    un->un_sys_blocksize);
24215 		}
24216 	}
24217 	mutex_exit(SD_MUTEX(un));
24218 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
24219 	return (rval);
24220 }
24221 
24222 
24223 /*
24224  *    Function: sd_delayed_cv_broadcast
24225  *
24226  * Description: Delayed cv_broadcast to allow for target to recover from media
24227  *		insertion.
24228  *
24229  *   Arguments: arg - driver soft state (unit) structure
24230  */
24231 
24232 static void
24233 sd_delayed_cv_broadcast(void *arg)
24234 {
24235 	struct sd_lun *un = arg;
24236 
24237 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
24238 
24239 	mutex_enter(SD_MUTEX(un));
24240 	un->un_dcvb_timeid = NULL;
24241 	cv_broadcast(&un->un_state_cv);
24242 	mutex_exit(SD_MUTEX(un));
24243 }
24244 
24245 
24246 /*
24247  *    Function: sd_media_watch_cb
24248  *
24249  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
24250  *		routine processes the TUR sense data and updates the driver
24251  *		state if a transition has occurred. The user thread
24252  *		(sd_check_media) is then signalled.
24253  *
24254  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24255  *			among multiple watches that share this callback function
24256  *		resultp - scsi watch facility result packet containing scsi
24257  *			  packet, status byte and sense data
24258  *
24259  * Return Code: 0 for success, -1 for failure
24260  */
24261 
24262 static int
24263 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24264 {
24265 	struct sd_lun			*un;
24266 	struct scsi_status		*statusp = resultp->statusp;
24267 	struct scsi_extended_sense	*sensep = resultp->sensep;
24268 	enum dkio_state			state = DKIO_NONE;
24269 	dev_t				dev = (dev_t)arg;
24270 	uchar_t				actual_sense_length;
24271 
24272 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24273 		return (-1);
24274 	}
24275 	actual_sense_length = resultp->actual_sense_length;
24276 
24277 	mutex_enter(SD_MUTEX(un));
24278 	SD_TRACE(SD_LOG_COMMON, un,
24279 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
24280 	    *((char *)statusp), (void *)sensep, actual_sense_length);
24281 
24282 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
24283 		un->un_mediastate = DKIO_DEV_GONE;
24284 		cv_broadcast(&un->un_state_cv);
24285 		mutex_exit(SD_MUTEX(un));
24286 
24287 		return (0);
24288 	}
24289 
24290 	/*
24291 	 * If there was a check condition then sensep points to valid sense data
24292 	 * If status was not a check condition but a reservation or busy status
24293 	 * then the new state is DKIO_NONE
24294 	 */
24295 	if (sensep != NULL) {
24296 		SD_INFO(SD_LOG_COMMON, un,
24297 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
24298 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
24299 		/* This routine only uses up to 13 bytes of sense data. */
24300 		if (actual_sense_length >= 13) {
24301 			if (sensep->es_key == KEY_UNIT_ATTENTION) {
24302 				if (sensep->es_add_code == 0x28) {
24303 					state = DKIO_INSERTED;
24304 				}
24305 			} else {
24306 				/*
24307 				 * if 02/04/02  means that the host
24308 				 * should send start command. Explicitly
24309 				 * leave the media state as is
24310 				 * (inserted) as the media is inserted
24311 				 * and host has stopped device for PM
24312 				 * reasons. Upon next true read/write
24313 				 * to this media will bring the
24314 				 * device to the right state good for
24315 				 * media access.
24316 				 */
24317 				if ((sensep->es_key == KEY_NOT_READY) &&
24318 				    (sensep->es_add_code == 0x3a)) {
24319 					state = DKIO_EJECTED;
24320 				}
24321 
24322 				/*
24323 				 * If the drivge is busy with an operation
24324 				 * or long write, keep the media in an
24325 				 * inserted state.
24326 				 */
24327 
24328 				if ((sensep->es_key == KEY_NOT_READY) &&
24329 				    (sensep->es_add_code == 0x04) &&
24330 				    ((sensep->es_qual_code == 0x02) ||
24331 				    (sensep->es_qual_code == 0x07) ||
24332 				    (sensep->es_qual_code == 0x08))) {
24333 					state = DKIO_INSERTED;
24334 				}
24335 			}
24336 		}
24337 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
24338 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
24339 		state = DKIO_INSERTED;
24340 	}
24341 
24342 	SD_TRACE(SD_LOG_COMMON, un,
24343 	    "sd_media_watch_cb: state=%x, specified=%x\n",
24344 	    state, un->un_specified_mediastate);
24345 
24346 	/*
24347 	 * now signal the waiting thread if this is *not* the specified state;
24348 	 * delay the signal if the state is DKIO_INSERTED to allow the target
24349 	 * to recover
24350 	 */
24351 	if (state != un->un_specified_mediastate) {
24352 		un->un_mediastate = state;
24353 		if (state == DKIO_INSERTED) {
24354 			/*
24355 			 * delay the signal to give the drive a chance
24356 			 * to do what it apparently needs to do
24357 			 */
24358 			SD_TRACE(SD_LOG_COMMON, un,
24359 			    "sd_media_watch_cb: delayed cv_broadcast\n");
24360 			if (un->un_dcvb_timeid == NULL) {
24361 				un->un_dcvb_timeid =
24362 				    timeout(sd_delayed_cv_broadcast, un,
24363 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
24364 			}
24365 		} else {
24366 			SD_TRACE(SD_LOG_COMMON, un,
24367 			    "sd_media_watch_cb: immediate cv_broadcast\n");
24368 			cv_broadcast(&un->un_state_cv);
24369 		}
24370 	}
24371 	mutex_exit(SD_MUTEX(un));
24372 	return (0);
24373 }
24374 
24375 
24376 /*
24377  *    Function: sd_dkio_get_temp
24378  *
24379  * Description: This routine is the driver entry point for handling ioctl
24380  *		requests to get the disk temperature.
24381  *
24382  *   Arguments: dev  - the device number
24383  *		arg  - pointer to user provided dk_temperature structure.
24384  *		flag - this argument is a pass through to ddi_copyxxx()
24385  *		       directly from the mode argument of ioctl().
24386  *
24387  * Return Code: 0
24388  *		EFAULT
24389  *		ENXIO
24390  *		EAGAIN
24391  */
24392 
24393 static int
24394 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
24395 {
24396 	struct sd_lun		*un = NULL;
24397 	struct dk_temperature	*dktemp = NULL;
24398 	uchar_t			*temperature_page;
24399 	int			rval = 0;
24400 	int			path_flag = SD_PATH_STANDARD;
24401 
24402 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24403 		return (ENXIO);
24404 	}
24405 
24406 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
24407 
24408 	/* copyin the disk temp argument to get the user flags */
24409 	if (ddi_copyin((void *)arg, dktemp,
24410 	    sizeof (struct dk_temperature), flag) != 0) {
24411 		rval = EFAULT;
24412 		goto done;
24413 	}
24414 
24415 	/* Initialize the temperature to invalid. */
24416 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24417 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24418 
24419 	/*
24420 	 * Note: Investigate removing the "bypass pm" semantic.
24421 	 * Can we just bypass PM always?
24422 	 */
24423 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
24424 		path_flag = SD_PATH_DIRECT;
24425 		ASSERT(!mutex_owned(&un->un_pm_mutex));
24426 		mutex_enter(&un->un_pm_mutex);
24427 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24428 			/*
24429 			 * If DKT_BYPASS_PM is set, and the drive happens to be
24430 			 * in low power mode, we can not wake it up, Need to
24431 			 * return EAGAIN.
24432 			 */
24433 			mutex_exit(&un->un_pm_mutex);
24434 			rval = EAGAIN;
24435 			goto done;
24436 		} else {
24437 			/*
24438 			 * Indicate to PM the device is busy. This is required
24439 			 * to avoid a race - i.e. the ioctl is issuing a
24440 			 * command and the pm framework brings down the device
24441 			 * to low power mode (possible power cut-off on some
24442 			 * platforms).
24443 			 */
24444 			mutex_exit(&un->un_pm_mutex);
24445 			if (sd_pm_entry(un) != DDI_SUCCESS) {
24446 				rval = EAGAIN;
24447 				goto done;
24448 			}
24449 		}
24450 	}
24451 
24452 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
24453 
24454 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
24455 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
24456 		goto done2;
24457 	}
24458 
24459 	/*
24460 	 * For the current temperature verify that the parameter length is 0x02
24461 	 * and the parameter code is 0x00
24462 	 */
24463 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
24464 	    (temperature_page[5] == 0x00)) {
24465 		if (temperature_page[9] == 0xFF) {
24466 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24467 		} else {
24468 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
24469 		}
24470 	}
24471 
24472 	/*
24473 	 * For the reference temperature verify that the parameter
24474 	 * length is 0x02 and the parameter code is 0x01
24475 	 */
24476 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
24477 	    (temperature_page[11] == 0x01)) {
24478 		if (temperature_page[15] == 0xFF) {
24479 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24480 		} else {
24481 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
24482 		}
24483 	}
24484 
24485 	/* Do the copyout regardless of the temperature commands status. */
24486 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
24487 	    flag) != 0) {
24488 		rval = EFAULT;
24489 	}
24490 
24491 done2:
24492 	if (path_flag == SD_PATH_DIRECT) {
24493 		sd_pm_exit(un);
24494 	}
24495 
24496 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
24497 done:
24498 	if (dktemp != NULL) {
24499 		kmem_free(dktemp, sizeof (struct dk_temperature));
24500 	}
24501 
24502 	return (rval);
24503 }
24504 
24505 
24506 /*
24507  *    Function: sd_log_page_supported
24508  *
24509  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
24510  *		supported log pages.
24511  *
24512  *   Arguments: un -
24513  *		log_page -
24514  *
24515  * Return Code: -1 - on error (log sense is optional and may not be supported).
24516  *		0  - log page not found.
24517  *  		1  - log page found.
24518  */
24519 
24520 static int
24521 sd_log_page_supported(struct sd_lun *un, int log_page)
24522 {
24523 	uchar_t *log_page_data;
24524 	int	i;
24525 	int	match = 0;
24526 	int	log_size;
24527 
24528 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
24529 
24530 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
24531 	    SD_PATH_DIRECT) != 0) {
24532 		SD_ERROR(SD_LOG_COMMON, un,
24533 		    "sd_log_page_supported: failed log page retrieval\n");
24534 		kmem_free(log_page_data, 0xFF);
24535 		return (-1);
24536 	}
24537 	log_size = log_page_data[3];
24538 
24539 	/*
24540 	 * The list of supported log pages start from the fourth byte. Check
24541 	 * until we run out of log pages or a match is found.
24542 	 */
24543 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
24544 		if (log_page_data[i] == log_page) {
24545 			match++;
24546 		}
24547 	}
24548 	kmem_free(log_page_data, 0xFF);
24549 	return (match);
24550 }
24551 
24552 
24553 /*
24554  *    Function: sd_mhdioc_failfast
24555  *
24556  * Description: This routine is the driver entry point for handling ioctl
24557  *		requests to enable/disable the multihost failfast option.
24558  *		(MHIOCENFAILFAST)
24559  *
24560  *   Arguments: dev	- the device number
24561  *		arg	- user specified probing interval.
24562  *		flag	- this argument is a pass through to ddi_copyxxx()
24563  *			  directly from the mode argument of ioctl().
24564  *
24565  * Return Code: 0
24566  *		EFAULT
24567  *		ENXIO
24568  */
24569 
24570 static int
24571 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24572 {
24573 	struct sd_lun	*un = NULL;
24574 	int		mh_time;
24575 	int		rval = 0;
24576 
24577 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24578 		return (ENXIO);
24579 	}
24580 
24581 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24582 		return (EFAULT);
24583 
24584 	if (mh_time) {
24585 		mutex_enter(SD_MUTEX(un));
24586 		un->un_resvd_status |= SD_FAILFAST;
24587 		mutex_exit(SD_MUTEX(un));
24588 		/*
24589 		 * If mh_time is INT_MAX, then this ioctl is being used for
24590 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24591 		 */
24592 		if (mh_time != INT_MAX) {
24593 			rval = sd_check_mhd(dev, mh_time);
24594 		}
24595 	} else {
24596 		(void) sd_check_mhd(dev, 0);
24597 		mutex_enter(SD_MUTEX(un));
24598 		un->un_resvd_status &= ~SD_FAILFAST;
24599 		mutex_exit(SD_MUTEX(un));
24600 	}
24601 	return (rval);
24602 }
24603 
24604 
24605 /*
24606  *    Function: sd_mhdioc_takeown
24607  *
24608  * Description: This routine is the driver entry point for handling ioctl
24609  *		requests to forcefully acquire exclusive access rights to the
24610  *		multihost disk (MHIOCTKOWN).
24611  *
24612  *   Arguments: dev	- the device number
24613  *		arg	- user provided structure specifying the delay
24614  *			  parameters in milliseconds
24615  *		flag	- this argument is a pass through to ddi_copyxxx()
24616  *			  directly from the mode argument of ioctl().
24617  *
24618  * Return Code: 0
24619  *		EFAULT
24620  *		ENXIO
24621  */
24622 
24623 static int
24624 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24625 {
24626 	struct sd_lun		*un = NULL;
24627 	struct mhioctkown	*tkown = NULL;
24628 	int			rval = 0;
24629 
24630 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24631 		return (ENXIO);
24632 	}
24633 
24634 	if (arg != NULL) {
24635 		tkown = (struct mhioctkown *)
24636 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24637 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24638 		if (rval != 0) {
24639 			rval = EFAULT;
24640 			goto error;
24641 		}
24642 	}
24643 
24644 	rval = sd_take_ownership(dev, tkown);
24645 	mutex_enter(SD_MUTEX(un));
24646 	if (rval == 0) {
24647 		un->un_resvd_status |= SD_RESERVE;
24648 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24649 			sd_reinstate_resv_delay =
24650 			    tkown->reinstate_resv_delay * 1000;
24651 		} else {
24652 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24653 		}
24654 		/*
24655 		 * Give the scsi_watch routine interval set by
24656 		 * the MHIOCENFAILFAST ioctl precedence here.
24657 		 */
24658 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24659 			mutex_exit(SD_MUTEX(un));
24660 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
24661 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24662 			    "sd_mhdioc_takeown : %d\n",
24663 			    sd_reinstate_resv_delay);
24664 		} else {
24665 			mutex_exit(SD_MUTEX(un));
24666 		}
24667 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24668 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24669 	} else {
24670 		un->un_resvd_status &= ~SD_RESERVE;
24671 		mutex_exit(SD_MUTEX(un));
24672 	}
24673 
24674 error:
24675 	if (tkown != NULL) {
24676 		kmem_free(tkown, sizeof (struct mhioctkown));
24677 	}
24678 	return (rval);
24679 }
24680 
24681 
24682 /*
24683  *    Function: sd_mhdioc_release
24684  *
24685  * Description: This routine is the driver entry point for handling ioctl
24686  *		requests to release exclusive access rights to the multihost
24687  *		disk (MHIOCRELEASE).
24688  *
24689  *   Arguments: dev	- the device number
24690  *
24691  * Return Code: 0
24692  *		ENXIO
24693  */
24694 
24695 static int
24696 sd_mhdioc_release(dev_t dev)
24697 {
24698 	struct sd_lun		*un = NULL;
24699 	timeout_id_t		resvd_timeid_save;
24700 	int			resvd_status_save;
24701 	int			rval = 0;
24702 
24703 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24704 		return (ENXIO);
24705 	}
24706 
24707 	mutex_enter(SD_MUTEX(un));
24708 	resvd_status_save = un->un_resvd_status;
24709 	un->un_resvd_status &=
24710 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24711 	if (un->un_resvd_timeid) {
24712 		resvd_timeid_save = un->un_resvd_timeid;
24713 		un->un_resvd_timeid = NULL;
24714 		mutex_exit(SD_MUTEX(un));
24715 		(void) untimeout(resvd_timeid_save);
24716 	} else {
24717 		mutex_exit(SD_MUTEX(un));
24718 	}
24719 
24720 	/*
24721 	 * destroy any pending timeout thread that may be attempting to
24722 	 * reinstate reservation on this device.
24723 	 */
24724 	sd_rmv_resv_reclaim_req(dev);
24725 
24726 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24727 		mutex_enter(SD_MUTEX(un));
24728 		if ((un->un_mhd_token) &&
24729 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24730 			mutex_exit(SD_MUTEX(un));
24731 			(void) sd_check_mhd(dev, 0);
24732 		} else {
24733 			mutex_exit(SD_MUTEX(un));
24734 		}
24735 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24736 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24737 	} else {
24738 		/*
24739 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24740 		 */
24741 		mutex_enter(SD_MUTEX(un));
24742 		un->un_resvd_status = resvd_status_save;
24743 		mutex_exit(SD_MUTEX(un));
24744 	}
24745 	return (rval);
24746 }
24747 
24748 
24749 /*
24750  *    Function: sd_mhdioc_register_devid
24751  *
24752  * Description: This routine is the driver entry point for handling ioctl
24753  *		requests to register the device id (MHIOCREREGISTERDEVID).
24754  *
24755  *		Note: The implementation for this ioctl has been updated to
24756  *		be consistent with the original PSARC case (1999/357)
24757  *		(4375899, 4241671, 4220005)
24758  *
24759  *   Arguments: dev	- the device number
24760  *
24761  * Return Code: 0
24762  *		ENXIO
24763  */
24764 
24765 static int
24766 sd_mhdioc_register_devid(dev_t dev)
24767 {
24768 	struct sd_lun	*un = NULL;
24769 	int		rval = 0;
24770 
24771 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24772 		return (ENXIO);
24773 	}
24774 
24775 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24776 
24777 	mutex_enter(SD_MUTEX(un));
24778 
24779 	/* If a devid already exists, de-register it */
24780 	if (un->un_devid != NULL) {
24781 		ddi_devid_unregister(SD_DEVINFO(un));
24782 		/*
24783 		 * After unregister devid, needs to free devid memory
24784 		 */
24785 		ddi_devid_free(un->un_devid);
24786 		un->un_devid = NULL;
24787 	}
24788 
24789 	/* Check for reservation conflict */
24790 	mutex_exit(SD_MUTEX(un));
24791 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
24792 	mutex_enter(SD_MUTEX(un));
24793 
24794 	switch (rval) {
24795 	case 0:
24796 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24797 		break;
24798 	case EACCES:
24799 		break;
24800 	default:
24801 		rval = EIO;
24802 	}
24803 
24804 	mutex_exit(SD_MUTEX(un));
24805 	return (rval);
24806 }
24807 
24808 
24809 /*
24810  *    Function: sd_mhdioc_inkeys
24811  *
24812  * Description: This routine is the driver entry point for handling ioctl
24813  *		requests to issue the SCSI-3 Persistent In Read Keys command
24814  *		to the device (MHIOCGRP_INKEYS).
24815  *
24816  *   Arguments: dev	- the device number
24817  *		arg	- user provided in_keys structure
24818  *		flag	- this argument is a pass through to ddi_copyxxx()
24819  *			  directly from the mode argument of ioctl().
24820  *
24821  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24822  *		ENXIO
24823  *		EFAULT
24824  */
24825 
24826 static int
24827 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24828 {
24829 	struct sd_lun		*un;
24830 	mhioc_inkeys_t		inkeys;
24831 	int			rval = 0;
24832 
24833 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24834 		return (ENXIO);
24835 	}
24836 
24837 #ifdef _MULTI_DATAMODEL
24838 	switch (ddi_model_convert_from(flag & FMODELS)) {
24839 	case DDI_MODEL_ILP32: {
24840 		struct mhioc_inkeys32	inkeys32;
24841 
24842 		if (ddi_copyin(arg, &inkeys32,
24843 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24844 			return (EFAULT);
24845 		}
24846 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24847 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24848 		    &inkeys, flag)) != 0) {
24849 			return (rval);
24850 		}
24851 		inkeys32.generation = inkeys.generation;
24852 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24853 		    flag) != 0) {
24854 			return (EFAULT);
24855 		}
24856 		break;
24857 	}
24858 	case DDI_MODEL_NONE:
24859 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
24860 		    flag) != 0) {
24861 			return (EFAULT);
24862 		}
24863 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24864 		    &inkeys, flag)) != 0) {
24865 			return (rval);
24866 		}
24867 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
24868 		    flag) != 0) {
24869 			return (EFAULT);
24870 		}
24871 		break;
24872 	}
24873 
24874 #else /* ! _MULTI_DATAMODEL */
24875 
24876 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
24877 		return (EFAULT);
24878 	}
24879 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
24880 	if (rval != 0) {
24881 		return (rval);
24882 	}
24883 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
24884 		return (EFAULT);
24885 	}
24886 
24887 #endif /* _MULTI_DATAMODEL */
24888 
24889 	return (rval);
24890 }
24891 
24892 
24893 /*
24894  *    Function: sd_mhdioc_inresv
24895  *
24896  * Description: This routine is the driver entry point for handling ioctl
24897  *		requests to issue the SCSI-3 Persistent In Read Reservations
24898  *		command to the device (MHIOCGRP_INKEYS).
24899  *
24900  *   Arguments: dev	- the device number
24901  *		arg	- user provided in_resv structure
24902  *		flag	- this argument is a pass through to ddi_copyxxx()
24903  *			  directly from the mode argument of ioctl().
24904  *
24905  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
24906  *		ENXIO
24907  *		EFAULT
24908  */
24909 
24910 static int
24911 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
24912 {
24913 	struct sd_lun		*un;
24914 	mhioc_inresvs_t		inresvs;
24915 	int			rval = 0;
24916 
24917 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24918 		return (ENXIO);
24919 	}
24920 
24921 #ifdef _MULTI_DATAMODEL
24922 
24923 	switch (ddi_model_convert_from(flag & FMODELS)) {
24924 	case DDI_MODEL_ILP32: {
24925 		struct mhioc_inresvs32	inresvs32;
24926 
24927 		if (ddi_copyin(arg, &inresvs32,
24928 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24929 			return (EFAULT);
24930 		}
24931 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
24932 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24933 		    &inresvs, flag)) != 0) {
24934 			return (rval);
24935 		}
24936 		inresvs32.generation = inresvs.generation;
24937 		if (ddi_copyout(&inresvs32, arg,
24938 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24939 			return (EFAULT);
24940 		}
24941 		break;
24942 	}
24943 	case DDI_MODEL_NONE:
24944 		if (ddi_copyin(arg, &inresvs,
24945 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24946 			return (EFAULT);
24947 		}
24948 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24949 		    &inresvs, flag)) != 0) {
24950 			return (rval);
24951 		}
24952 		if (ddi_copyout(&inresvs, arg,
24953 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24954 			return (EFAULT);
24955 		}
24956 		break;
24957 	}
24958 
24959 #else /* ! _MULTI_DATAMODEL */
24960 
24961 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
24962 		return (EFAULT);
24963 	}
24964 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
24965 	if (rval != 0) {
24966 		return (rval);
24967 	}
24968 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
24969 		return (EFAULT);
24970 	}
24971 
24972 #endif /* ! _MULTI_DATAMODEL */
24973 
24974 	return (rval);
24975 }
24976 
24977 
24978 /*
24979  * The following routines support the clustering functionality described below
24980  * and implement lost reservation reclaim functionality.
24981  *
24982  * Clustering
24983  * ----------
24984  * The clustering code uses two different, independent forms of SCSI
24985  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
24986  * Persistent Group Reservations. For any particular disk, it will use either
24987  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
24988  *
24989  * SCSI-2
24990  * The cluster software takes ownership of a multi-hosted disk by issuing the
24991  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
24992  * MHIOCRELEASE ioctl.Closely related is the MHIOCENFAILFAST ioctl -- a cluster,
24993  * just after taking ownership of the disk with the MHIOCTKOWN ioctl then issues
24994  * the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the driver. The
24995  * meaning of failfast is that if the driver (on this host) ever encounters the
24996  * scsi error return code RESERVATION_CONFLICT from the device, it should
24997  * immediately panic the host. The motivation for this ioctl is that if this
24998  * host does encounter reservation conflict, the underlying cause is that some
24999  * other host of the cluster has decided that this host is no longer in the
25000  * cluster and has seized control of the disks for itself. Since this host is no
25001  * longer in the cluster, it ought to panic itself. The MHIOCENFAILFAST ioctl
25002  * does two things:
25003  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
25004  *      error to panic the host
25005  *      (b) it sets up a periodic timer to test whether this host still has
25006  *      "access" (in that no other host has reserved the device):  if the
25007  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
25008  *      purpose of that periodic timer is to handle scenarios where the host is
25009  *      otherwise temporarily quiescent, temporarily doing no real i/o.
25010  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
25011  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
25012  * the device itself.
25013  *
25014  * SCSI-3 PGR
25015  * A direct semantic implementation of the SCSI-3 Persistent Reservation
25016  * facility is supported through the shared multihost disk ioctls
25017  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
25018  * MHIOCGRP_PREEMPTANDABORT)
25019  *
25020  * Reservation Reclaim:
25021  * --------------------
25022  * To support the lost reservation reclaim operations this driver creates a
25023  * single thread to handle reinstating reservations on all devices that have
25024  * lost reservations sd_resv_reclaim_requests are logged for all devices that
25025  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
25026  * and the reservation reclaim thread loops through the requests to regain the
25027  * lost reservations.
25028  */
25029 
25030 /*
25031  *    Function: sd_check_mhd()
25032  *
25033  * Description: This function sets up and submits a scsi watch request or
25034  *		terminates an existing watch request. This routine is used in
25035  *		support of reservation reclaim.
25036  *
25037  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
25038  *			 among multiple watches that share the callback function
25039  *		interval - the number of microseconds specifying the watch
25040  *			   interval for issuing TEST UNIT READY commands. If
25041  *			   set to 0 the watch should be terminated. If the
25042  *			   interval is set to 0 and if the device is required
25043  *			   to hold reservation while disabling failfast, the
25044  *			   watch is restarted with an interval of
25045  *			   reinstate_resv_delay.
25046  *
25047  * Return Code: 0	   - Successful submit/terminate of scsi watch request
25048  *		ENXIO      - Indicates an invalid device was specified
25049  *		EAGAIN     - Unable to submit the scsi watch request
25050  */
25051 
25052 static int
25053 sd_check_mhd(dev_t dev, int interval)
25054 {
25055 	struct sd_lun	*un;
25056 	opaque_t	token;
25057 
25058 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25059 		return (ENXIO);
25060 	}
25061 
25062 	/* is this a watch termination request? */
25063 	if (interval == 0) {
25064 		mutex_enter(SD_MUTEX(un));
25065 		/* if there is an existing watch task then terminate it */
25066 		if (un->un_mhd_token) {
25067 			token = un->un_mhd_token;
25068 			un->un_mhd_token = NULL;
25069 			mutex_exit(SD_MUTEX(un));
25070 			(void) scsi_watch_request_terminate(token,
25071 			    SCSI_WATCH_TERMINATE_WAIT);
25072 			mutex_enter(SD_MUTEX(un));
25073 		} else {
25074 			mutex_exit(SD_MUTEX(un));
25075 			/*
25076 			 * Note: If we return here we don't check for the
25077 			 * failfast case. This is the original legacy
25078 			 * implementation but perhaps we should be checking
25079 			 * the failfast case.
25080 			 */
25081 			return (0);
25082 		}
25083 		/*
25084 		 * If the device is required to hold reservation while
25085 		 * disabling failfast, we need to restart the scsi_watch
25086 		 * routine with an interval of reinstate_resv_delay.
25087 		 */
25088 		if (un->un_resvd_status & SD_RESERVE) {
25089 			interval = sd_reinstate_resv_delay/1000;
25090 		} else {
25091 			/* no failfast so bail */
25092 			mutex_exit(SD_MUTEX(un));
25093 			return (0);
25094 		}
25095 		mutex_exit(SD_MUTEX(un));
25096 	}
25097 
25098 	/*
25099 	 * adjust minimum time interval to 1 second,
25100 	 * and convert from msecs to usecs
25101 	 */
25102 	if (interval > 0 && interval < 1000) {
25103 		interval = 1000;
25104 	}
25105 	interval *= 1000;
25106 
25107 	/*
25108 	 * submit the request to the scsi_watch service
25109 	 */
25110 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
25111 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
25112 	if (token == NULL) {
25113 		return (EAGAIN);
25114 	}
25115 
25116 	/*
25117 	 * save token for termination later on
25118 	 */
25119 	mutex_enter(SD_MUTEX(un));
25120 	un->un_mhd_token = token;
25121 	mutex_exit(SD_MUTEX(un));
25122 	return (0);
25123 }
25124 
25125 
25126 /*
25127  *    Function: sd_mhd_watch_cb()
25128  *
25129  * Description: This function is the call back function used by the scsi watch
25130  *		facility. The scsi watch facility sends the "Test Unit Ready"
25131  *		and processes the status. If applicable (i.e. a "Unit Attention"
25132  *		status and automatic "Request Sense" not used) the scsi watch
25133  *		facility will send a "Request Sense" and retrieve the sense data
25134  *		to be passed to this callback function. In either case the
25135  *		automatic "Request Sense" or the facility submitting one, this
25136  *		callback is passed the status and sense data.
25137  *
25138  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25139  *			among multiple watches that share this callback function
25140  *		resultp - scsi watch facility result packet containing scsi
25141  *			  packet, status byte and sense data
25142  *
25143  * Return Code: 0 - continue the watch task
25144  *		non-zero - terminate the watch task
25145  */
25146 
25147 static int
25148 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
25149 {
25150 	struct sd_lun			*un;
25151 	struct scsi_status		*statusp;
25152 	struct scsi_extended_sense	*sensep;
25153 	struct scsi_pkt			*pkt;
25154 	uchar_t				actual_sense_length;
25155 	dev_t  				dev = (dev_t)arg;
25156 
25157 	ASSERT(resultp != NULL);
25158 	statusp			= resultp->statusp;
25159 	sensep			= resultp->sensep;
25160 	pkt			= resultp->pkt;
25161 	actual_sense_length	= resultp->actual_sense_length;
25162 
25163 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25164 		return (ENXIO);
25165 	}
25166 
25167 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25168 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
25169 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
25170 
25171 	/* Begin processing of the status and/or sense data */
25172 	if (pkt->pkt_reason != CMD_CMPLT) {
25173 		/* Handle the incomplete packet */
25174 		sd_mhd_watch_incomplete(un, pkt);
25175 		return (0);
25176 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
25177 		if (*((unsigned char *)statusp)
25178 		    == STATUS_RESERVATION_CONFLICT) {
25179 			/*
25180 			 * Handle a reservation conflict by panicking if
25181 			 * configured for failfast or by logging the conflict
25182 			 * and updating the reservation status
25183 			 */
25184 			mutex_enter(SD_MUTEX(un));
25185 			if ((un->un_resvd_status & SD_FAILFAST) &&
25186 			    (sd_failfast_enable)) {
25187 				sd_panic_for_res_conflict(un);
25188 				/*NOTREACHED*/
25189 			}
25190 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25191 			    "sd_mhd_watch_cb: Reservation Conflict\n");
25192 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
25193 			mutex_exit(SD_MUTEX(un));
25194 		}
25195 	}
25196 
25197 	if (sensep != NULL) {
25198 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
25199 			mutex_enter(SD_MUTEX(un));
25200 			if ((sensep->es_add_code == SD_SCSI_RESET_SENSE_CODE) &&
25201 			    (un->un_resvd_status & SD_RESERVE)) {
25202 				/*
25203 				 * The additional sense code indicates a power
25204 				 * on or bus device reset has occurred; update
25205 				 * the reservation status.
25206 				 */
25207 				un->un_resvd_status |=
25208 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25209 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25210 				    "sd_mhd_watch_cb: Lost Reservation\n");
25211 			}
25212 		} else {
25213 			return (0);
25214 		}
25215 	} else {
25216 		mutex_enter(SD_MUTEX(un));
25217 	}
25218 
25219 	if ((un->un_resvd_status & SD_RESERVE) &&
25220 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
25221 		if (un->un_resvd_status & SD_WANT_RESERVE) {
25222 			/*
25223 			 * A reset occurred in between the last probe and this
25224 			 * one so if a timeout is pending cancel it.
25225 			 */
25226 			if (un->un_resvd_timeid) {
25227 				timeout_id_t temp_id = un->un_resvd_timeid;
25228 				un->un_resvd_timeid = NULL;
25229 				mutex_exit(SD_MUTEX(un));
25230 				(void) untimeout(temp_id);
25231 				mutex_enter(SD_MUTEX(un));
25232 			}
25233 			un->un_resvd_status &= ~SD_WANT_RESERVE;
25234 		}
25235 		if (un->un_resvd_timeid == 0) {
25236 			/* Schedule a timeout to handle the lost reservation */
25237 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
25238 			    (void *)dev,
25239 			    drv_usectohz(sd_reinstate_resv_delay));
25240 		}
25241 	}
25242 	mutex_exit(SD_MUTEX(un));
25243 	return (0);
25244 }
25245 
25246 
25247 /*
25248  *    Function: sd_mhd_watch_incomplete()
25249  *
25250  * Description: This function is used to find out why a scsi pkt sent by the
25251  *		scsi watch facility was not completed. Under some scenarios this
25252  *		routine will return. Otherwise it will send a bus reset to see
25253  *		if the drive is still online.
25254  *
25255  *   Arguments: un  - driver soft state (unit) structure
25256  *		pkt - incomplete scsi pkt
25257  */
25258 
25259 static void
25260 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
25261 {
25262 	int	be_chatty;
25263 	int	perr;
25264 
25265 	ASSERT(pkt != NULL);
25266 	ASSERT(un != NULL);
25267 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
25268 	perr		= (pkt->pkt_statistics & STAT_PERR);
25269 
25270 	mutex_enter(SD_MUTEX(un));
25271 	if (un->un_state == SD_STATE_DUMPING) {
25272 		mutex_exit(SD_MUTEX(un));
25273 		return;
25274 	}
25275 
25276 	switch (pkt->pkt_reason) {
25277 	case CMD_UNX_BUS_FREE:
25278 		/*
25279 		 * If we had a parity error that caused the target to drop BSY*,
25280 		 * don't be chatty about it.
25281 		 */
25282 		if (perr && be_chatty) {
25283 			be_chatty = 0;
25284 		}
25285 		break;
25286 	case CMD_TAG_REJECT:
25287 		/*
25288 		 * The SCSI-2 spec states that a tag reject will be sent by the
25289 		 * target if tagged queuing is not supported. A tag reject may
25290 		 * also be sent during certain initialization periods or to
25291 		 * control internal resources. For the latter case the target
25292 		 * may also return Queue Full.
25293 		 *
25294 		 * If this driver receives a tag reject from a target that is
25295 		 * going through an init period or controlling internal
25296 		 * resources tagged queuing will be disabled. This is a less
25297 		 * than optimal behavior but the driver is unable to determine
25298 		 * the target state and assumes tagged queueing is not supported
25299 		 */
25300 		pkt->pkt_flags = 0;
25301 		un->un_tagflags = 0;
25302 
25303 		if (un->un_f_opt_queueing == TRUE) {
25304 			un->un_throttle = min(un->un_throttle, 3);
25305 		} else {
25306 			un->un_throttle = 1;
25307 		}
25308 		mutex_exit(SD_MUTEX(un));
25309 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
25310 		mutex_enter(SD_MUTEX(un));
25311 		break;
25312 	case CMD_INCOMPLETE:
25313 		/*
25314 		 * The transport stopped with an abnormal state, fallthrough and
25315 		 * reset the target and/or bus unless selection did not complete
25316 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
25317 		 * go through a target/bus reset
25318 		 */
25319 		if (pkt->pkt_state == STATE_GOT_BUS) {
25320 			break;
25321 		}
25322 		/*FALLTHROUGH*/
25323 
25324 	case CMD_TIMEOUT:
25325 	default:
25326 		/*
25327 		 * The lun may still be running the command, so a lun reset
25328 		 * should be attempted. If the lun reset fails or cannot be
25329 		 * issued, than try a target reset. Lastly try a bus reset.
25330 		 */
25331 		if ((pkt->pkt_statistics &
25332 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
25333 			int reset_retval = 0;
25334 			mutex_exit(SD_MUTEX(un));
25335 			if (un->un_f_allow_bus_device_reset == TRUE) {
25336 				if (un->un_f_lun_reset_enabled == TRUE) {
25337 					reset_retval =
25338 					    scsi_reset(SD_ADDRESS(un),
25339 					    RESET_LUN);
25340 				}
25341 				if (reset_retval == 0) {
25342 					reset_retval =
25343 					    scsi_reset(SD_ADDRESS(un),
25344 					    RESET_TARGET);
25345 				}
25346 			}
25347 			if (reset_retval == 0) {
25348 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25349 			}
25350 			mutex_enter(SD_MUTEX(un));
25351 		}
25352 		break;
25353 	}
25354 
25355 	/* A device/bus reset has occurred; update the reservation status. */
25356 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
25357 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
25358 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25359 			un->un_resvd_status |=
25360 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25361 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25362 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
25363 		}
25364 	}
25365 
25366 	/*
25367 	 * The disk has been turned off; Update the device state.
25368 	 *
25369 	 * Note: Should we be offlining the disk here?
25370 	 */
25371 	if (pkt->pkt_state == STATE_GOT_BUS) {
25372 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
25373 		    "Disk not responding to selection\n");
25374 		if (un->un_state != SD_STATE_OFFLINE) {
25375 			New_state(un, SD_STATE_OFFLINE);
25376 		}
25377 	} else if (be_chatty) {
25378 		/*
25379 		 * suppress messages if they are all the same pkt reason;
25380 		 * with TQ, many (up to 256) are returned with the same
25381 		 * pkt_reason
25382 		 */
25383 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
25384 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25385 			    "sd_mhd_watch_incomplete: "
25386 			    "SCSI transport failed: reason '%s'\n",
25387 			    scsi_rname(pkt->pkt_reason));
25388 		}
25389 	}
25390 	un->un_last_pkt_reason = pkt->pkt_reason;
25391 	mutex_exit(SD_MUTEX(un));
25392 }
25393 
25394 
25395 /*
25396  *    Function: sd_sname()
25397  *
25398  * Description: This is a simple little routine to return a string containing
25399  *		a printable description of command status byte for use in
25400  *		logging.
25401  *
25402  *   Arguments: status - pointer to a status byte
25403  *
25404  * Return Code: char * - string containing status description.
25405  */
25406 
25407 static char *
25408 sd_sname(uchar_t status)
25409 {
25410 	switch (status & STATUS_MASK) {
25411 	case STATUS_GOOD:
25412 		return ("good status");
25413 	case STATUS_CHECK:
25414 		return ("check condition");
25415 	case STATUS_MET:
25416 		return ("condition met");
25417 	case STATUS_BUSY:
25418 		return ("busy");
25419 	case STATUS_INTERMEDIATE:
25420 		return ("intermediate");
25421 	case STATUS_INTERMEDIATE_MET:
25422 		return ("intermediate - condition met");
25423 	case STATUS_RESERVATION_CONFLICT:
25424 		return ("reservation_conflict");
25425 	case STATUS_TERMINATED:
25426 		return ("command terminated");
25427 	case STATUS_QFULL:
25428 		return ("queue full");
25429 	default:
25430 		return ("<unknown status>");
25431 	}
25432 }
25433 
25434 
25435 /*
25436  *    Function: sd_mhd_resvd_recover()
25437  *
25438  * Description: This function adds a reservation entry to the
25439  *		sd_resv_reclaim_request list and signals the reservation
25440  *		reclaim thread that there is work pending. If the reservation
25441  *		reclaim thread has not been previously created this function
25442  *		will kick it off.
25443  *
25444  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25445  *			among multiple watches that share this callback function
25446  *
25447  *     Context: This routine is called by timeout() and is run in interrupt
25448  *		context. It must not sleep or call other functions which may
25449  *		sleep.
25450  */
25451 
25452 static void
25453 sd_mhd_resvd_recover(void *arg)
25454 {
25455 	dev_t			dev = (dev_t)arg;
25456 	struct sd_lun		*un;
25457 	struct sd_thr_request	*sd_treq = NULL;
25458 	struct sd_thr_request	*sd_cur = NULL;
25459 	struct sd_thr_request	*sd_prev = NULL;
25460 	int			already_there = 0;
25461 
25462 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25463 		return;
25464 	}
25465 
25466 	mutex_enter(SD_MUTEX(un));
25467 	un->un_resvd_timeid = NULL;
25468 	if (un->un_resvd_status & SD_WANT_RESERVE) {
25469 		/*
25470 		 * There was a reset so don't issue the reserve, allow the
25471 		 * sd_mhd_watch_cb callback function to notice this and
25472 		 * reschedule the timeout for reservation.
25473 		 */
25474 		mutex_exit(SD_MUTEX(un));
25475 		return;
25476 	}
25477 	mutex_exit(SD_MUTEX(un));
25478 
25479 	/*
25480 	 * Add this device to the sd_resv_reclaim_request list and the
25481 	 * sd_resv_reclaim_thread should take care of the rest.
25482 	 *
25483 	 * Note: We can't sleep in this context so if the memory allocation
25484 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
25485 	 * reschedule the timeout for reservation.  (4378460)
25486 	 */
25487 	sd_treq = (struct sd_thr_request *)
25488 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
25489 	if (sd_treq == NULL) {
25490 		return;
25491 	}
25492 
25493 	sd_treq->sd_thr_req_next = NULL;
25494 	sd_treq->dev = dev;
25495 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25496 	if (sd_tr.srq_thr_req_head == NULL) {
25497 		sd_tr.srq_thr_req_head = sd_treq;
25498 	} else {
25499 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
25500 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
25501 			if (sd_cur->dev == dev) {
25502 				/*
25503 				 * already in Queue so don't log
25504 				 * another request for the device
25505 				 */
25506 				already_there = 1;
25507 				break;
25508 			}
25509 			sd_prev = sd_cur;
25510 		}
25511 		if (!already_there) {
25512 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
25513 			    "logging request for %lx\n", dev);
25514 			sd_prev->sd_thr_req_next = sd_treq;
25515 		} else {
25516 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
25517 		}
25518 	}
25519 
25520 	/*
25521 	 * Create a kernel thread to do the reservation reclaim and free up this
25522 	 * thread. We cannot block this thread while we go away to do the
25523 	 * reservation reclaim
25524 	 */
25525 	if (sd_tr.srq_resv_reclaim_thread == NULL)
25526 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
25527 		    sd_resv_reclaim_thread, NULL,
25528 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
25529 
25530 	/* Tell the reservation reclaim thread that it has work to do */
25531 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
25532 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25533 }
25534 
25535 /*
25536  *    Function: sd_resv_reclaim_thread()
25537  *
25538  * Description: This function implements the reservation reclaim operations
25539  *
25540  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
25541  *		      among multiple watches that share this callback function
25542  */
25543 
25544 static void
25545 sd_resv_reclaim_thread()
25546 {
25547 	struct sd_lun		*un;
25548 	struct sd_thr_request	*sd_mhreq;
25549 
25550 	/* Wait for work */
25551 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25552 	if (sd_tr.srq_thr_req_head == NULL) {
25553 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25554 		    &sd_tr.srq_resv_reclaim_mutex);
25555 	}
25556 
25557 	/* Loop while we have work */
25558 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25559 		un = ddi_get_soft_state(sd_state,
25560 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25561 		if (un == NULL) {
25562 			/*
25563 			 * softstate structure is NULL so just
25564 			 * dequeue the request and continue
25565 			 */
25566 			sd_tr.srq_thr_req_head =
25567 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25568 			kmem_free(sd_tr.srq_thr_cur_req,
25569 			    sizeof (struct sd_thr_request));
25570 			continue;
25571 		}
25572 
25573 		/* dequeue the request */
25574 		sd_mhreq = sd_tr.srq_thr_cur_req;
25575 		sd_tr.srq_thr_req_head =
25576 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25577 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25578 
25579 		/*
25580 		 * Reclaim reservation only if SD_RESERVE is still set. There
25581 		 * may have been a call to MHIOCRELEASE before we got here.
25582 		 */
25583 		mutex_enter(SD_MUTEX(un));
25584 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25585 			/*
25586 			 * Note: The SD_LOST_RESERVE flag is cleared before
25587 			 * reclaiming the reservation. If this is done after the
25588 			 * call to sd_reserve_release a reservation loss in the
25589 			 * window between pkt completion of reserve cmd and
25590 			 * mutex_enter below may not be recognized
25591 			 */
25592 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25593 			mutex_exit(SD_MUTEX(un));
25594 
25595 			if (sd_reserve_release(sd_mhreq->dev,
25596 			    SD_RESERVE) == 0) {
25597 				mutex_enter(SD_MUTEX(un));
25598 				un->un_resvd_status |= SD_RESERVE;
25599 				mutex_exit(SD_MUTEX(un));
25600 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25601 				    "sd_resv_reclaim_thread: "
25602 				    "Reservation Recovered\n");
25603 			} else {
25604 				mutex_enter(SD_MUTEX(un));
25605 				un->un_resvd_status |= SD_LOST_RESERVE;
25606 				mutex_exit(SD_MUTEX(un));
25607 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25608 				    "sd_resv_reclaim_thread: Failed "
25609 				    "Reservation Recovery\n");
25610 			}
25611 		} else {
25612 			mutex_exit(SD_MUTEX(un));
25613 		}
25614 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25615 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25616 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25617 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25618 		/*
25619 		 * wakeup the destroy thread if anyone is waiting on
25620 		 * us to complete.
25621 		 */
25622 		cv_signal(&sd_tr.srq_inprocess_cv);
25623 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25624 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25625 	}
25626 
25627 	/*
25628 	 * cleanup the sd_tr structure now that this thread will not exist
25629 	 */
25630 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25631 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25632 	sd_tr.srq_resv_reclaim_thread = NULL;
25633 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25634 	thread_exit();
25635 }
25636 
25637 
25638 /*
25639  *    Function: sd_rmv_resv_reclaim_req()
25640  *
25641  * Description: This function removes any pending reservation reclaim requests
25642  *		for the specified device.
25643  *
25644  *   Arguments: dev - the device 'dev_t'
25645  */
25646 
25647 static void
25648 sd_rmv_resv_reclaim_req(dev_t dev)
25649 {
25650 	struct sd_thr_request *sd_mhreq;
25651 	struct sd_thr_request *sd_prev;
25652 
25653 	/* Remove a reservation reclaim request from the list */
25654 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25655 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25656 		/*
25657 		 * We are attempting to reinstate reservation for
25658 		 * this device. We wait for sd_reserve_release()
25659 		 * to return before we return.
25660 		 */
25661 		cv_wait(&sd_tr.srq_inprocess_cv,
25662 		    &sd_tr.srq_resv_reclaim_mutex);
25663 	} else {
25664 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25665 		if (sd_mhreq && sd_mhreq->dev == dev) {
25666 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25667 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25668 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25669 			return;
25670 		}
25671 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25672 			if (sd_mhreq && sd_mhreq->dev == dev) {
25673 				break;
25674 			}
25675 			sd_prev = sd_mhreq;
25676 		}
25677 		if (sd_mhreq != NULL) {
25678 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25679 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25680 		}
25681 	}
25682 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25683 }
25684 
25685 
25686 /*
25687  *    Function: sd_mhd_reset_notify_cb()
25688  *
25689  * Description: This is a call back function for scsi_reset_notify. This
25690  *		function updates the softstate reserved status and logs the
25691  *		reset. The driver scsi watch facility callback function
25692  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25693  *		will reclaim the reservation.
25694  *
25695  *   Arguments: arg  - driver soft state (unit) structure
25696  */
25697 
25698 static void
25699 sd_mhd_reset_notify_cb(caddr_t arg)
25700 {
25701 	struct sd_lun *un = (struct sd_lun *)arg;
25702 
25703 	mutex_enter(SD_MUTEX(un));
25704 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25705 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25706 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25707 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25708 	}
25709 	mutex_exit(SD_MUTEX(un));
25710 }
25711 
25712 
25713 /*
25714  *    Function: sd_take_ownership()
25715  *
25716  * Description: This routine implements an algorithm to achieve a stable
25717  *		reservation on disks which don't implement priority reserve,
25718  *		and makes sure that other host lose re-reservation attempts.
25719  *		This algorithm contains of a loop that keeps issuing the RESERVE
25720  *		for some period of time (min_ownership_delay, default 6 seconds)
25721  *		During that loop, it looks to see if there has been a bus device
25722  *		reset or bus reset (both of which cause an existing reservation
25723  *		to be lost). If the reservation is lost issue RESERVE until a
25724  *		period of min_ownership_delay with no resets has gone by, or
25725  *		until max_ownership_delay has expired. This loop ensures that
25726  *		the host really did manage to reserve the device, in spite of
25727  *		resets. The looping for min_ownership_delay (default six
25728  *		seconds) is important to early generation clustering products,
25729  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25730  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25731  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25732  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25733  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25734  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25735  *		no longer "owns" the disk and will have panicked itself.  Thus,
25736  *		the host issuing the MHIOCTKOWN is assured (with timing
25737  *		dependencies) that by the time it actually starts to use the
25738  *		disk for real work, the old owner is no longer accessing it.
25739  *
25740  *		min_ownership_delay is the minimum amount of time for which the
25741  *		disk must be reserved continuously devoid of resets before the
25742  *		MHIOCTKOWN ioctl will return success.
25743  *
25744  *		max_ownership_delay indicates the amount of time by which the
25745  *		take ownership should succeed or timeout with an error.
25746  *
25747  *   Arguments: dev - the device 'dev_t'
25748  *		*p  - struct containing timing info.
25749  *
25750  * Return Code: 0 for success or error code
25751  */
25752 
25753 static int
25754 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25755 {
25756 	struct sd_lun	*un;
25757 	int		rval;
25758 	int		err;
25759 	int		reservation_count   = 0;
25760 	int		min_ownership_delay =  6000000; /* in usec */
25761 	int		max_ownership_delay = 30000000; /* in usec */
25762 	clock_t		start_time;	/* starting time of this algorithm */
25763 	clock_t		end_time;	/* time limit for giving up */
25764 	clock_t		ownership_time;	/* time limit for stable ownership */
25765 	clock_t		current_time;
25766 	clock_t		previous_current_time;
25767 
25768 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25769 		return (ENXIO);
25770 	}
25771 
25772 	/*
25773 	 * Attempt a device reservation. A priority reservation is requested.
25774 	 */
25775 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25776 	    != SD_SUCCESS) {
25777 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25778 		    "sd_take_ownership: return(1)=%d\n", rval);
25779 		return (rval);
25780 	}
25781 
25782 	/* Update the softstate reserved status to indicate the reservation */
25783 	mutex_enter(SD_MUTEX(un));
25784 	un->un_resvd_status |= SD_RESERVE;
25785 	un->un_resvd_status &=
25786 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25787 	mutex_exit(SD_MUTEX(un));
25788 
25789 	if (p != NULL) {
25790 		if (p->min_ownership_delay != 0) {
25791 			min_ownership_delay = p->min_ownership_delay * 1000;
25792 		}
25793 		if (p->max_ownership_delay != 0) {
25794 			max_ownership_delay = p->max_ownership_delay * 1000;
25795 		}
25796 	}
25797 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25798 	    "sd_take_ownership: min, max delays: %d, %d\n",
25799 	    min_ownership_delay, max_ownership_delay);
25800 
25801 	start_time = ddi_get_lbolt();
25802 	current_time	= start_time;
25803 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25804 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25805 
25806 	while (current_time - end_time < 0) {
25807 		delay(drv_usectohz(500000));
25808 
25809 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25810 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25811 				mutex_enter(SD_MUTEX(un));
25812 				rval = (un->un_resvd_status &
25813 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25814 				mutex_exit(SD_MUTEX(un));
25815 				break;
25816 			}
25817 		}
25818 		previous_current_time = current_time;
25819 		current_time = ddi_get_lbolt();
25820 		mutex_enter(SD_MUTEX(un));
25821 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25822 			ownership_time = ddi_get_lbolt() +
25823 			    drv_usectohz(min_ownership_delay);
25824 			reservation_count = 0;
25825 		} else {
25826 			reservation_count++;
25827 		}
25828 		un->un_resvd_status |= SD_RESERVE;
25829 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25830 		mutex_exit(SD_MUTEX(un));
25831 
25832 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25833 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25834 		    "reservation=%s\n", (current_time - previous_current_time),
25835 		    reservation_count ? "ok" : "reclaimed");
25836 
25837 		if (current_time - ownership_time >= 0 &&
25838 		    reservation_count >= 4) {
25839 			rval = 0; /* Achieved a stable ownership */
25840 			break;
25841 		}
25842 		if (current_time - end_time >= 0) {
25843 			rval = EACCES; /* No ownership in max possible time */
25844 			break;
25845 		}
25846 	}
25847 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25848 	    "sd_take_ownership: return(2)=%d\n", rval);
25849 	return (rval);
25850 }
25851 
25852 
25853 /*
25854  *    Function: sd_reserve_release()
25855  *
25856  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25857  *		PRIORITY RESERVE commands based on a user specified command type
25858  *
25859  *   Arguments: dev - the device 'dev_t'
25860  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
25861  *		      SD_RESERVE, SD_RELEASE
25862  *
25863  * Return Code: 0 or Error Code
25864  */
25865 
25866 static int
25867 sd_reserve_release(dev_t dev, int cmd)
25868 {
25869 	struct uscsi_cmd	*com = NULL;
25870 	struct sd_lun		*un = NULL;
25871 	char			cdb[CDB_GROUP0];
25872 	int			rval;
25873 
25874 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
25875 	    (cmd == SD_PRIORITY_RESERVE));
25876 
25877 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25878 		return (ENXIO);
25879 	}
25880 
25881 	/* instantiate and initialize the command and cdb */
25882 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25883 	bzero(cdb, CDB_GROUP0);
25884 	com->uscsi_flags   = USCSI_SILENT;
25885 	com->uscsi_timeout = un->un_reserve_release_time;
25886 	com->uscsi_cdblen  = CDB_GROUP0;
25887 	com->uscsi_cdb	   = cdb;
25888 	if (cmd == SD_RELEASE) {
25889 		cdb[0] = SCMD_RELEASE;
25890 	} else {
25891 		cdb[0] = SCMD_RESERVE;
25892 	}
25893 
25894 	/* Send the command. */
25895 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
25896 	    UIO_SYSSPACE, SD_PATH_STANDARD);
25897 
25898 	/*
25899 	 * "break" a reservation that is held by another host, by issuing a
25900 	 * reset if priority reserve is desired, and we could not get the
25901 	 * device.
25902 	 */
25903 	if ((cmd == SD_PRIORITY_RESERVE) &&
25904 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25905 		/*
25906 		 * First try to reset the LUN. If we cannot, then try a target
25907 		 * reset, followed by a bus reset if the target reset fails.
25908 		 */
25909 		int reset_retval = 0;
25910 		if (un->un_f_lun_reset_enabled == TRUE) {
25911 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
25912 		}
25913 		if (reset_retval == 0) {
25914 			/* The LUN reset either failed or was not issued */
25915 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25916 		}
25917 		if ((reset_retval == 0) &&
25918 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
25919 			rval = EIO;
25920 			kmem_free(com, sizeof (*com));
25921 			return (rval);
25922 		}
25923 
25924 		bzero(com, sizeof (struct uscsi_cmd));
25925 		com->uscsi_flags   = USCSI_SILENT;
25926 		com->uscsi_cdb	   = cdb;
25927 		com->uscsi_cdblen  = CDB_GROUP0;
25928 		com->uscsi_timeout = 5;
25929 
25930 		/*
25931 		 * Reissue the last reserve command, this time without request
25932 		 * sense.  Assume that it is just a regular reserve command.
25933 		 */
25934 		rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
25935 		    UIO_SYSSPACE, SD_PATH_STANDARD);
25936 	}
25937 
25938 	/* Return an error if still getting a reservation conflict. */
25939 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25940 		rval = EACCES;
25941 	}
25942 
25943 	kmem_free(com, sizeof (*com));
25944 	return (rval);
25945 }
25946 
25947 
25948 #define	SD_NDUMP_RETRIES	12
25949 /*
25950  *	System Crash Dump routine
25951  */
25952 
25953 static int
25954 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
25955 {
25956 	int		instance;
25957 	int		partition;
25958 	int		i;
25959 	int		err;
25960 	struct sd_lun	*un;
25961 	struct dk_map	*lp;
25962 	struct scsi_pkt *wr_pktp;
25963 	struct buf	*wr_bp;
25964 	struct buf	wr_buf;
25965 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
25966 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
25967 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
25968 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
25969 	size_t		io_start_offset;
25970 	int		doing_rmw = FALSE;
25971 	int		rval;
25972 #if defined(__i386) || defined(__amd64)
25973 	ssize_t dma_resid;
25974 	daddr_t oblkno;
25975 #endif
25976 
25977 	instance = SDUNIT(dev);
25978 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
25979 	    (!un->un_f_geometry_is_valid) || ISCD(un)) {
25980 		return (ENXIO);
25981 	}
25982 
25983 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
25984 
25985 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
25986 
25987 	partition = SDPART(dev);
25988 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
25989 
25990 	/* Validate blocks to dump at against partition size. */
25991 	lp = &un->un_map[partition];
25992 	if ((blkno + nblk) > lp->dkl_nblk) {
25993 		SD_TRACE(SD_LOG_DUMP, un,
25994 		    "sddump: dump range larger than partition: "
25995 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25996 		    blkno, nblk, lp->dkl_nblk);
25997 		return (EINVAL);
25998 	}
25999 
26000 	mutex_enter(&un->un_pm_mutex);
26001 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
26002 		struct scsi_pkt *start_pktp;
26003 
26004 		mutex_exit(&un->un_pm_mutex);
26005 
26006 		/*
26007 		 * use pm framework to power on HBA 1st
26008 		 */
26009 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
26010 
26011 		/*
26012 		 * Dump no long uses sdpower to power on a device, it's
26013 		 * in-line here so it can be done in polled mode.
26014 		 */
26015 
26016 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
26017 
26018 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
26019 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
26020 
26021 		if (start_pktp == NULL) {
26022 			/* We were not given a SCSI packet, fail. */
26023 			return (EIO);
26024 		}
26025 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
26026 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
26027 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
26028 		start_pktp->pkt_flags = FLAG_NOINTR;
26029 
26030 		mutex_enter(SD_MUTEX(un));
26031 		SD_FILL_SCSI1_LUN(un, start_pktp);
26032 		mutex_exit(SD_MUTEX(un));
26033 		/*
26034 		 * Scsi_poll returns 0 (success) if the command completes and
26035 		 * the status block is STATUS_GOOD.
26036 		 */
26037 		if (sd_scsi_poll(un, start_pktp) != 0) {
26038 			scsi_destroy_pkt(start_pktp);
26039 			return (EIO);
26040 		}
26041 		scsi_destroy_pkt(start_pktp);
26042 		(void) sd_ddi_pm_resume(un);
26043 	} else {
26044 		mutex_exit(&un->un_pm_mutex);
26045 	}
26046 
26047 	mutex_enter(SD_MUTEX(un));
26048 	un->un_throttle = 0;
26049 
26050 	/*
26051 	 * The first time through, reset the specific target device.
26052 	 * However, when cpr calls sddump we know that sd is in a
26053 	 * a good state so no bus reset is required.
26054 	 * Clear sense data via Request Sense cmd.
26055 	 * In sddump we don't care about allow_bus_device_reset anymore
26056 	 */
26057 
26058 	if ((un->un_state != SD_STATE_SUSPENDED) &&
26059 	    (un->un_state != SD_STATE_DUMPING)) {
26060 
26061 		New_state(un, SD_STATE_DUMPING);
26062 
26063 		if (un->un_f_is_fibre == FALSE) {
26064 			mutex_exit(SD_MUTEX(un));
26065 			/*
26066 			 * Attempt a bus reset for parallel scsi.
26067 			 *
26068 			 * Note: A bus reset is required because on some host
26069 			 * systems (i.e. E420R) a bus device reset is
26070 			 * insufficient to reset the state of the target.
26071 			 *
26072 			 * Note: Don't issue the reset for fibre-channel,
26073 			 * because this tends to hang the bus (loop) for
26074 			 * too long while everyone is logging out and in
26075 			 * and the deadman timer for dumping will fire
26076 			 * before the dump is complete.
26077 			 */
26078 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
26079 				mutex_enter(SD_MUTEX(un));
26080 				Restore_state(un);
26081 				mutex_exit(SD_MUTEX(un));
26082 				return (EIO);
26083 			}
26084 
26085 			/* Delay to give the device some recovery time. */
26086 			drv_usecwait(10000);
26087 
26088 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
26089 				SD_INFO(SD_LOG_DUMP, un,
26090 					"sddump: sd_send_polled_RQS failed\n");
26091 			}
26092 			mutex_enter(SD_MUTEX(un));
26093 		}
26094 	}
26095 
26096 	/*
26097 	 * Convert the partition-relative block number to a
26098 	 * disk physical block number.
26099 	 */
26100 	blkno += un->un_offset[partition];
26101 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
26102 
26103 
26104 	/*
26105 	 * Check if the device has a non-512 block size.
26106 	 */
26107 	wr_bp = NULL;
26108 	if (NOT_DEVBSIZE(un)) {
26109 		tgt_byte_offset = blkno * un->un_sys_blocksize;
26110 		tgt_byte_count = nblk * un->un_sys_blocksize;
26111 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
26112 		    (tgt_byte_count % un->un_tgt_blocksize)) {
26113 			doing_rmw = TRUE;
26114 			/*
26115 			 * Calculate the block number and number of block
26116 			 * in terms of the media block size.
26117 			 */
26118 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26119 			tgt_nblk =
26120 			    ((tgt_byte_offset + tgt_byte_count +
26121 				(un->un_tgt_blocksize - 1)) /
26122 				un->un_tgt_blocksize) - tgt_blkno;
26123 
26124 			/*
26125 			 * Invoke the routine which is going to do read part
26126 			 * of read-modify-write.
26127 			 * Note that this routine returns a pointer to
26128 			 * a valid bp in wr_bp.
26129 			 */
26130 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
26131 			    &wr_bp);
26132 			if (err) {
26133 				mutex_exit(SD_MUTEX(un));
26134 				return (err);
26135 			}
26136 			/*
26137 			 * Offset is being calculated as -
26138 			 * (original block # * system block size) -
26139 			 * (new block # * target block size)
26140 			 */
26141 			io_start_offset =
26142 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
26143 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
26144 
26145 			ASSERT((io_start_offset >= 0) &&
26146 			    (io_start_offset < un->un_tgt_blocksize));
26147 			/*
26148 			 * Do the modify portion of read modify write.
26149 			 */
26150 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
26151 			    (size_t)nblk * un->un_sys_blocksize);
26152 		} else {
26153 			doing_rmw = FALSE;
26154 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26155 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
26156 		}
26157 
26158 		/* Convert blkno and nblk to target blocks */
26159 		blkno = tgt_blkno;
26160 		nblk = tgt_nblk;
26161 	} else {
26162 		wr_bp = &wr_buf;
26163 		bzero(wr_bp, sizeof (struct buf));
26164 		wr_bp->b_flags		= B_BUSY;
26165 		wr_bp->b_un.b_addr	= addr;
26166 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
26167 		wr_bp->b_resid		= 0;
26168 	}
26169 
26170 	mutex_exit(SD_MUTEX(un));
26171 
26172 	/*
26173 	 * Obtain a SCSI packet for the write command.
26174 	 * It should be safe to call the allocator here without
26175 	 * worrying about being locked for DVMA mapping because
26176 	 * the address we're passed is already a DVMA mapping
26177 	 *
26178 	 * We are also not going to worry about semaphore ownership
26179 	 * in the dump buffer. Dumping is single threaded at present.
26180 	 */
26181 
26182 	wr_pktp = NULL;
26183 
26184 #if defined(__i386) || defined(__amd64)
26185 	dma_resid = wr_bp->b_bcount;
26186 	oblkno = blkno;
26187 	while (dma_resid != 0) {
26188 #endif
26189 
26190 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26191 		wr_bp->b_flags &= ~B_ERROR;
26192 
26193 #if defined(__i386) || defined(__amd64)
26194 		blkno = oblkno +
26195 			((wr_bp->b_bcount - dma_resid) /
26196 			    un->un_tgt_blocksize);
26197 		nblk = dma_resid / un->un_tgt_blocksize;
26198 
26199 		if (wr_pktp) {
26200 			/* Partial DMA transfers after initial transfer */
26201 			rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
26202 			    blkno, nblk);
26203 		} else {
26204 			/* Initial transfer */
26205 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26206 			    un->un_pkt_flags, NULL_FUNC, NULL,
26207 			    blkno, nblk);
26208 		}
26209 #else
26210 		rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26211 		    0, NULL_FUNC, NULL, blkno, nblk);
26212 #endif
26213 
26214 		if (rval == 0) {
26215 			/* We were given a SCSI packet, continue. */
26216 			break;
26217 		}
26218 
26219 		if (i == 0) {
26220 			if (wr_bp->b_flags & B_ERROR) {
26221 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26222 				    "no resources for dumping; "
26223 				    "error code: 0x%x, retrying",
26224 				    geterror(wr_bp));
26225 			} else {
26226 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26227 				    "no resources for dumping; retrying");
26228 			}
26229 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
26230 			if (wr_bp->b_flags & B_ERROR) {
26231 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26232 				    "no resources for dumping; error code: "
26233 				    "0x%x, retrying\n", geterror(wr_bp));
26234 			}
26235 		} else {
26236 			if (wr_bp->b_flags & B_ERROR) {
26237 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26238 				    "no resources for dumping; "
26239 				    "error code: 0x%x, retries failed, "
26240 				    "giving up.\n", geterror(wr_bp));
26241 			} else {
26242 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26243 				    "no resources for dumping; "
26244 				    "retries failed, giving up.\n");
26245 			}
26246 			mutex_enter(SD_MUTEX(un));
26247 			Restore_state(un);
26248 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
26249 				mutex_exit(SD_MUTEX(un));
26250 				scsi_free_consistent_buf(wr_bp);
26251 			} else {
26252 				mutex_exit(SD_MUTEX(un));
26253 			}
26254 			return (EIO);
26255 		}
26256 		drv_usecwait(10000);
26257 	}
26258 
26259 #if defined(__i386) || defined(__amd64)
26260 	/*
26261 	 * save the resid from PARTIAL_DMA
26262 	 */
26263 	dma_resid = wr_pktp->pkt_resid;
26264 	if (dma_resid != 0)
26265 		nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
26266 	wr_pktp->pkt_resid = 0;
26267 #endif
26268 
26269 	/* SunBug 1222170 */
26270 	wr_pktp->pkt_flags = FLAG_NOINTR;
26271 
26272 	err = EIO;
26273 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26274 
26275 		/*
26276 		 * Scsi_poll returns 0 (success) if the command completes and
26277 		 * the status block is STATUS_GOOD.  We should only check
26278 		 * errors if this condition is not true.  Even then we should
26279 		 * send our own request sense packet only if we have a check
26280 		 * condition and auto request sense has not been performed by
26281 		 * the hba.
26282 		 */
26283 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
26284 
26285 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
26286 		    (wr_pktp->pkt_resid == 0)) {
26287 			err = SD_SUCCESS;
26288 			break;
26289 		}
26290 
26291 		/*
26292 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
26293 		 */
26294 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
26295 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26296 			    "Device is gone\n");
26297 			break;
26298 		}
26299 
26300 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
26301 			SD_INFO(SD_LOG_DUMP, un,
26302 			    "sddump: write failed with CHECK, try # %d\n", i);
26303 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
26304 				(void) sd_send_polled_RQS(un);
26305 			}
26306 
26307 			continue;
26308 		}
26309 
26310 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
26311 			int reset_retval = 0;
26312 
26313 			SD_INFO(SD_LOG_DUMP, un,
26314 			    "sddump: write failed with BUSY, try # %d\n", i);
26315 
26316 			if (un->un_f_lun_reset_enabled == TRUE) {
26317 				reset_retval = scsi_reset(SD_ADDRESS(un),
26318 				    RESET_LUN);
26319 			}
26320 			if (reset_retval == 0) {
26321 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26322 			}
26323 			(void) sd_send_polled_RQS(un);
26324 
26325 		} else {
26326 			SD_INFO(SD_LOG_DUMP, un,
26327 			    "sddump: write failed with 0x%x, try # %d\n",
26328 			    SD_GET_PKT_STATUS(wr_pktp), i);
26329 			mutex_enter(SD_MUTEX(un));
26330 			sd_reset_target(un, wr_pktp);
26331 			mutex_exit(SD_MUTEX(un));
26332 		}
26333 
26334 		/*
26335 		 * If we are not getting anywhere with lun/target resets,
26336 		 * let's reset the bus.
26337 		 */
26338 		if (i == SD_NDUMP_RETRIES/2) {
26339 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26340 			(void) sd_send_polled_RQS(un);
26341 		}
26342 
26343 	}
26344 #if defined(__i386) || defined(__amd64)
26345 	}	/* dma_resid */
26346 #endif
26347 
26348 	scsi_destroy_pkt(wr_pktp);
26349 	mutex_enter(SD_MUTEX(un));
26350 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
26351 		mutex_exit(SD_MUTEX(un));
26352 		scsi_free_consistent_buf(wr_bp);
26353 	} else {
26354 		mutex_exit(SD_MUTEX(un));
26355 	}
26356 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
26357 	return (err);
26358 }
26359 
26360 /*
26361  *    Function: sd_scsi_poll()
26362  *
26363  * Description: This is a wrapper for the scsi_poll call.
26364  *
26365  *   Arguments: sd_lun - The unit structure
26366  *              scsi_pkt - The scsi packet being sent to the device.
26367  *
26368  * Return Code: 0 - Command completed successfully with good status
26369  *             -1 - Command failed.  This could indicate a check condition
26370  *                  or other status value requiring recovery action.
26371  *
26372  */
26373 
26374 static int
26375 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
26376 {
26377 	int status;
26378 
26379 	ASSERT(un != NULL);
26380 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26381 	ASSERT(pktp != NULL);
26382 
26383 	status = SD_SUCCESS;
26384 
26385 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
26386 		pktp->pkt_flags |= un->un_tagflags;
26387 		pktp->pkt_flags &= ~FLAG_NODISCON;
26388 	}
26389 
26390 	status = sd_ddi_scsi_poll(pktp);
26391 	/*
26392 	 * Scsi_poll returns 0 (success) if the command completes and the
26393 	 * status block is STATUS_GOOD.  We should only check errors if this
26394 	 * condition is not true.  Even then we should send our own request
26395 	 * sense packet only if we have a check condition and auto
26396 	 * request sense has not been performed by the hba.
26397 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
26398 	 */
26399 	if ((status != SD_SUCCESS) &&
26400 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
26401 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
26402 	    (pktp->pkt_reason != CMD_DEV_GONE))
26403 		(void) sd_send_polled_RQS(un);
26404 
26405 	return (status);
26406 }
26407 
26408 /*
26409  *    Function: sd_send_polled_RQS()
26410  *
26411  * Description: This sends the request sense command to a device.
26412  *
26413  *   Arguments: sd_lun - The unit structure
26414  *
26415  * Return Code: 0 - Command completed successfully with good status
26416  *             -1 - Command failed.
26417  *
26418  */
26419 
26420 static int
26421 sd_send_polled_RQS(struct sd_lun *un)
26422 {
26423 	int	ret_val;
26424 	struct	scsi_pkt	*rqs_pktp;
26425 	struct	buf		*rqs_bp;
26426 
26427 	ASSERT(un != NULL);
26428 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26429 
26430 	ret_val = SD_SUCCESS;
26431 
26432 	rqs_pktp = un->un_rqs_pktp;
26433 	rqs_bp	 = un->un_rqs_bp;
26434 
26435 	mutex_enter(SD_MUTEX(un));
26436 
26437 	if (un->un_sense_isbusy) {
26438 		ret_val = SD_FAILURE;
26439 		mutex_exit(SD_MUTEX(un));
26440 		return (ret_val);
26441 	}
26442 
26443 	/*
26444 	 * If the request sense buffer (and packet) is not in use,
26445 	 * let's set the un_sense_isbusy and send our packet
26446 	 */
26447 	un->un_sense_isbusy 	= 1;
26448 	rqs_pktp->pkt_resid  	= 0;
26449 	rqs_pktp->pkt_reason 	= 0;
26450 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
26451 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
26452 
26453 	mutex_exit(SD_MUTEX(un));
26454 
26455 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
26456 	    " 0x%p\n", rqs_bp->b_un.b_addr);
26457 
26458 	/*
26459 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
26460 	 * axle - it has a call into us!
26461 	 */
26462 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
26463 		SD_INFO(SD_LOG_COMMON, un,
26464 		    "sd_send_polled_RQS: RQS failed\n");
26465 	}
26466 
26467 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
26468 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
26469 
26470 	mutex_enter(SD_MUTEX(un));
26471 	un->un_sense_isbusy = 0;
26472 	mutex_exit(SD_MUTEX(un));
26473 
26474 	return (ret_val);
26475 }
26476 
26477 /*
26478  * Defines needed for localized version of the scsi_poll routine.
26479  */
26480 #define	SD_CSEC		10000			/* usecs */
26481 #define	SD_SEC_TO_CSEC	(1000000/SD_CSEC)
26482 
26483 
26484 /*
26485  *    Function: sd_ddi_scsi_poll()
26486  *
26487  * Description: Localized version of the scsi_poll routine.  The purpose is to
26488  *		send a scsi_pkt to a device as a polled command.  This version
26489  *		is to ensure more robust handling of transport errors.
26490  *		Specifically this routine cures not ready, coming ready
26491  *		transition for power up and reset of sonoma's.  This can take
26492  *		up to 45 seconds for power-on and 20 seconds for reset of a
26493  * 		sonoma lun.
26494  *
26495  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
26496  *
26497  * Return Code: 0 - Command completed successfully with good status
26498  *             -1 - Command failed.
26499  *
26500  */
26501 
26502 static int
26503 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26504 {
26505 	int busy_count;
26506 	int timeout;
26507 	int rval = SD_FAILURE;
26508 	int savef;
26509 	struct scsi_extended_sense *sensep;
26510 	long savet;
26511 	void (*savec)();
26512 	/*
26513 	 * The following is defined in machdep.c and is used in determining if
26514 	 * the scsi transport system will do polled I/O instead of interrupt
26515 	 * I/O when called from xx_dump().
26516 	 */
26517 	extern int do_polled_io;
26518 
26519 	/*
26520 	 * save old flags in pkt, to restore at end
26521 	 */
26522 	savef = pkt->pkt_flags;
26523 	savec = pkt->pkt_comp;
26524 	savet = pkt->pkt_time;
26525 
26526 	pkt->pkt_flags |= FLAG_NOINTR;
26527 
26528 	/*
26529 	 * XXX there is nothing in the SCSA spec that states that we should not
26530 	 * do a callback for polled cmds; however, removing this will break sd
26531 	 * and probably other target drivers
26532 	 */
26533 	pkt->pkt_comp = NULL;
26534 
26535 	/*
26536 	 * we don't like a polled command without timeout.
26537 	 * 60 seconds seems long enough.
26538 	 */
26539 	if (pkt->pkt_time == 0) {
26540 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26541 	}
26542 
26543 	/*
26544 	 * Send polled cmd.
26545 	 *
26546 	 * We do some error recovery for various errors.  Tran_busy,
26547 	 * queue full, and non-dispatched commands are retried every 10 msec.
26548 	 * as they are typically transient failures.  Busy status and Not
26549 	 * Ready are retried every second as this status takes a while to
26550 	 * change.  Unit attention is retried for pkt_time (60) times
26551 	 * with no delay.
26552 	 */
26553 	timeout = pkt->pkt_time * SD_SEC_TO_CSEC;
26554 
26555 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26556 		int rc;
26557 		int poll_delay;
26558 
26559 		/*
26560 		 * Initialize pkt status variables.
26561 		 */
26562 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26563 
26564 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26565 			if (rc != TRAN_BUSY) {
26566 				/* Transport failed - give up. */
26567 				break;
26568 			} else {
26569 				/* Transport busy - try again. */
26570 				poll_delay = 1 * SD_CSEC; /* 10 msec */
26571 			}
26572 		} else {
26573 			/*
26574 			 * Transport accepted - check pkt status.
26575 			 */
26576 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26577 			if (pkt->pkt_reason == CMD_CMPLT &&
26578 			    rc == STATUS_CHECK &&
26579 			    pkt->pkt_state & STATE_ARQ_DONE) {
26580 				struct scsi_arq_status *arqstat =
26581 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26582 
26583 				sensep = &arqstat->sts_sensedata;
26584 			} else {
26585 				sensep = NULL;
26586 			}
26587 
26588 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26589 			    (rc == STATUS_GOOD)) {
26590 				/* No error - we're done */
26591 				rval = SD_SUCCESS;
26592 				break;
26593 
26594 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26595 				/* Lost connection - give up */
26596 				break;
26597 
26598 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26599 			    (pkt->pkt_state == 0)) {
26600 				/* Pkt not dispatched - try again. */
26601 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
26602 
26603 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26604 			    (rc == STATUS_QFULL)) {
26605 				/* Queue full - try again. */
26606 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
26607 
26608 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26609 			    (rc == STATUS_BUSY)) {
26610 				/* Busy - try again. */
26611 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
26612 				busy_count += (SD_SEC_TO_CSEC - 1);
26613 
26614 			} else if ((sensep != NULL) &&
26615 			    (sensep->es_key == KEY_UNIT_ATTENTION)) {
26616 				/* Unit Attention - try again */
26617 				busy_count += (SD_SEC_TO_CSEC - 1); /* 1 */
26618 				continue;
26619 
26620 			} else if ((sensep != NULL) &&
26621 			    (sensep->es_key == KEY_NOT_READY) &&
26622 			    (sensep->es_add_code == 0x04) &&
26623 			    (sensep->es_qual_code == 0x01)) {
26624 				/* Not ready -> ready - try again. */
26625 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
26626 				busy_count += (SD_SEC_TO_CSEC - 1);
26627 
26628 			} else {
26629 				/* BAD status - give up. */
26630 				break;
26631 			}
26632 		}
26633 
26634 		if ((curthread->t_flag & T_INTR_THREAD) == 0 &&
26635 		    !do_polled_io) {
26636 			delay(drv_usectohz(poll_delay));
26637 		} else {
26638 			/* we busy wait during cpr_dump or interrupt threads */
26639 			drv_usecwait(poll_delay);
26640 		}
26641 	}
26642 
26643 	pkt->pkt_flags = savef;
26644 	pkt->pkt_comp = savec;
26645 	pkt->pkt_time = savet;
26646 	return (rval);
26647 }
26648 
26649 
26650 /*
26651  *    Function: sd_persistent_reservation_in_read_keys
26652  *
26653  * Description: This routine is the driver entry point for handling CD-ROM
26654  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26655  *		by sending the SCSI-3 PRIN commands to the device.
26656  *		Processes the read keys command response by copying the
26657  *		reservation key information into the user provided buffer.
26658  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26659  *
26660  *   Arguments: un   -  Pointer to soft state struct for the target.
26661  *		usrp -	user provided pointer to multihost Persistent In Read
26662  *			Keys structure (mhioc_inkeys_t)
26663  *		flag -	this argument is a pass through to ddi_copyxxx()
26664  *			directly from the mode argument of ioctl().
26665  *
26666  * Return Code: 0   - Success
26667  *		EACCES
26668  *		ENOTSUP
26669  *		errno return code from sd_send_scsi_cmd()
26670  *
26671  *     Context: Can sleep. Does not return until command is completed.
26672  */
26673 
26674 static int
26675 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26676     mhioc_inkeys_t *usrp, int flag)
26677 {
26678 #ifdef _MULTI_DATAMODEL
26679 	struct mhioc_key_list32	li32;
26680 #endif
26681 	sd_prin_readkeys_t	*in;
26682 	mhioc_inkeys_t		*ptr;
26683 	mhioc_key_list_t	li;
26684 	uchar_t			*data_bufp;
26685 	int 			data_len;
26686 	int			rval;
26687 	size_t			copysz;
26688 
26689 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26690 		return (EINVAL);
26691 	}
26692 	bzero(&li, sizeof (mhioc_key_list_t));
26693 
26694 	/*
26695 	 * Get the listsize from user
26696 	 */
26697 #ifdef _MULTI_DATAMODEL
26698 
26699 	switch (ddi_model_convert_from(flag & FMODELS)) {
26700 	case DDI_MODEL_ILP32:
26701 		copysz = sizeof (struct mhioc_key_list32);
26702 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26703 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26704 			    "sd_persistent_reservation_in_read_keys: "
26705 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26706 			rval = EFAULT;
26707 			goto done;
26708 		}
26709 		li.listsize = li32.listsize;
26710 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26711 		break;
26712 
26713 	case DDI_MODEL_NONE:
26714 		copysz = sizeof (mhioc_key_list_t);
26715 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26716 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26717 			    "sd_persistent_reservation_in_read_keys: "
26718 			    "failed ddi_copyin: mhioc_key_list_t\n");
26719 			rval = EFAULT;
26720 			goto done;
26721 		}
26722 		break;
26723 	}
26724 
26725 #else /* ! _MULTI_DATAMODEL */
26726 	copysz = sizeof (mhioc_key_list_t);
26727 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26728 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26729 		    "sd_persistent_reservation_in_read_keys: "
26730 		    "failed ddi_copyin: mhioc_key_list_t\n");
26731 		rval = EFAULT;
26732 		goto done;
26733 	}
26734 #endif
26735 
26736 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26737 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26738 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26739 
26740 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
26741 	    data_len, data_bufp)) != 0) {
26742 		goto done;
26743 	}
26744 	in = (sd_prin_readkeys_t *)data_bufp;
26745 	ptr->generation = BE_32(in->generation);
26746 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26747 
26748 	/*
26749 	 * Return the min(listsize, listlen) keys
26750 	 */
26751 #ifdef _MULTI_DATAMODEL
26752 
26753 	switch (ddi_model_convert_from(flag & FMODELS)) {
26754 	case DDI_MODEL_ILP32:
26755 		li32.listlen = li.listlen;
26756 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26757 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26758 			    "sd_persistent_reservation_in_read_keys: "
26759 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26760 			rval = EFAULT;
26761 			goto done;
26762 		}
26763 		break;
26764 
26765 	case DDI_MODEL_NONE:
26766 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26767 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26768 			    "sd_persistent_reservation_in_read_keys: "
26769 			    "failed ddi_copyout: mhioc_key_list_t\n");
26770 			rval = EFAULT;
26771 			goto done;
26772 		}
26773 		break;
26774 	}
26775 
26776 #else /* ! _MULTI_DATAMODEL */
26777 
26778 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26779 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26780 		    "sd_persistent_reservation_in_read_keys: "
26781 		    "failed ddi_copyout: mhioc_key_list_t\n");
26782 		rval = EFAULT;
26783 		goto done;
26784 	}
26785 
26786 #endif /* _MULTI_DATAMODEL */
26787 
26788 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
26789 	    li.listsize * MHIOC_RESV_KEY_SIZE);
26790 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
26791 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26792 		    "sd_persistent_reservation_in_read_keys: "
26793 		    "failed ddi_copyout: keylist\n");
26794 		rval = EFAULT;
26795 	}
26796 done:
26797 	kmem_free(data_bufp, data_len);
26798 	return (rval);
26799 }
26800 
26801 
26802 /*
26803  *    Function: sd_persistent_reservation_in_read_resv
26804  *
26805  * Description: This routine is the driver entry point for handling CD-ROM
26806  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
26807  *		by sending the SCSI-3 PRIN commands to the device.
26808  *		Process the read persistent reservations command response by
26809  *		copying the reservation information into the user provided
26810  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
26811  *
26812  *   Arguments: un   -  Pointer to soft state struct for the target.
26813  *		usrp -	user provided pointer to multihost Persistent In Read
26814  *			Keys structure (mhioc_inkeys_t)
26815  *		flag -	this argument is a pass through to ddi_copyxxx()
26816  *			directly from the mode argument of ioctl().
26817  *
26818  * Return Code: 0   - Success
26819  *		EACCES
26820  *		ENOTSUP
26821  *		errno return code from sd_send_scsi_cmd()
26822  *
26823  *     Context: Can sleep. Does not return until command is completed.
26824  */
26825 
26826 static int
26827 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
26828     mhioc_inresvs_t *usrp, int flag)
26829 {
26830 #ifdef _MULTI_DATAMODEL
26831 	struct mhioc_resv_desc_list32 resvlist32;
26832 #endif
26833 	sd_prin_readresv_t	*in;
26834 	mhioc_inresvs_t		*ptr;
26835 	sd_readresv_desc_t	*readresv_ptr;
26836 	mhioc_resv_desc_list_t	resvlist;
26837 	mhioc_resv_desc_t 	resvdesc;
26838 	uchar_t			*data_bufp;
26839 	int 			data_len;
26840 	int			rval;
26841 	int			i;
26842 	size_t			copysz;
26843 	mhioc_resv_desc_t	*bufp;
26844 
26845 	if ((ptr = usrp) == NULL) {
26846 		return (EINVAL);
26847 	}
26848 
26849 	/*
26850 	 * Get the listsize from user
26851 	 */
26852 #ifdef _MULTI_DATAMODEL
26853 	switch (ddi_model_convert_from(flag & FMODELS)) {
26854 	case DDI_MODEL_ILP32:
26855 		copysz = sizeof (struct mhioc_resv_desc_list32);
26856 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
26857 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26858 			    "sd_persistent_reservation_in_read_resv: "
26859 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26860 			rval = EFAULT;
26861 			goto done;
26862 		}
26863 		resvlist.listsize = resvlist32.listsize;
26864 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
26865 		break;
26866 
26867 	case DDI_MODEL_NONE:
26868 		copysz = sizeof (mhioc_resv_desc_list_t);
26869 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26870 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26871 			    "sd_persistent_reservation_in_read_resv: "
26872 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26873 			rval = EFAULT;
26874 			goto done;
26875 		}
26876 		break;
26877 	}
26878 #else /* ! _MULTI_DATAMODEL */
26879 	copysz = sizeof (mhioc_resv_desc_list_t);
26880 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26881 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26882 		    "sd_persistent_reservation_in_read_resv: "
26883 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26884 		rval = EFAULT;
26885 		goto done;
26886 	}
26887 #endif /* ! _MULTI_DATAMODEL */
26888 
26889 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
26890 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
26891 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26892 
26893 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
26894 	    data_len, data_bufp)) != 0) {
26895 		goto done;
26896 	}
26897 	in = (sd_prin_readresv_t *)data_bufp;
26898 	ptr->generation = BE_32(in->generation);
26899 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
26900 
26901 	/*
26902 	 * Return the min(listsize, listlen( keys
26903 	 */
26904 #ifdef _MULTI_DATAMODEL
26905 
26906 	switch (ddi_model_convert_from(flag & FMODELS)) {
26907 	case DDI_MODEL_ILP32:
26908 		resvlist32.listlen = resvlist.listlen;
26909 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
26910 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26911 			    "sd_persistent_reservation_in_read_resv: "
26912 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26913 			rval = EFAULT;
26914 			goto done;
26915 		}
26916 		break;
26917 
26918 	case DDI_MODEL_NONE:
26919 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26920 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26921 			    "sd_persistent_reservation_in_read_resv: "
26922 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26923 			rval = EFAULT;
26924 			goto done;
26925 		}
26926 		break;
26927 	}
26928 
26929 #else /* ! _MULTI_DATAMODEL */
26930 
26931 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26932 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26933 		    "sd_persistent_reservation_in_read_resv: "
26934 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26935 		rval = EFAULT;
26936 		goto done;
26937 	}
26938 
26939 #endif /* ! _MULTI_DATAMODEL */
26940 
26941 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
26942 	bufp = resvlist.list;
26943 	copysz = sizeof (mhioc_resv_desc_t);
26944 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
26945 	    i++, readresv_ptr++, bufp++) {
26946 
26947 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
26948 		    MHIOC_RESV_KEY_SIZE);
26949 		resvdesc.type  = readresv_ptr->type;
26950 		resvdesc.scope = readresv_ptr->scope;
26951 		resvdesc.scope_specific_addr =
26952 		    BE_32(readresv_ptr->scope_specific_addr);
26953 
26954 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
26955 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26956 			    "sd_persistent_reservation_in_read_resv: "
26957 			    "failed ddi_copyout: resvlist\n");
26958 			rval = EFAULT;
26959 			goto done;
26960 		}
26961 	}
26962 done:
26963 	kmem_free(data_bufp, data_len);
26964 	return (rval);
26965 }
26966 
26967 
26968 /*
26969  *    Function: sr_change_blkmode()
26970  *
26971  * Description: This routine is the driver entry point for handling CD-ROM
26972  *		block mode ioctl requests. Support for returning and changing
26973  *		the current block size in use by the device is implemented. The
26974  *		LBA size is changed via a MODE SELECT Block Descriptor.
26975  *
26976  *		This routine issues a mode sense with an allocation length of
26977  *		12 bytes for the mode page header and a single block descriptor.
26978  *
26979  *   Arguments: dev - the device 'dev_t'
26980  *		cmd - the request type; one of CDROMGBLKMODE (get) or
26981  *		      CDROMSBLKMODE (set)
26982  *		data - current block size or requested block size
26983  *		flag - this argument is a pass through to ddi_copyxxx() directly
26984  *		       from the mode argument of ioctl().
26985  *
26986  * Return Code: the code returned by sd_send_scsi_cmd()
26987  *		EINVAL if invalid arguments are provided
26988  *		EFAULT if ddi_copyxxx() fails
26989  *		ENXIO if fail ddi_get_soft_state
26990  *		EIO if invalid mode sense block descriptor length
26991  *
26992  */
26993 
26994 static int
26995 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
26996 {
26997 	struct sd_lun			*un = NULL;
26998 	struct mode_header		*sense_mhp, *select_mhp;
26999 	struct block_descriptor		*sense_desc, *select_desc;
27000 	int				current_bsize;
27001 	int				rval = EINVAL;
27002 	uchar_t				*sense = NULL;
27003 	uchar_t				*select = NULL;
27004 
27005 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
27006 
27007 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27008 		return (ENXIO);
27009 	}
27010 
27011 	/*
27012 	 * The block length is changed via the Mode Select block descriptor, the
27013 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
27014 	 * required as part of this routine. Therefore the mode sense allocation
27015 	 * length is specified to be the length of a mode page header and a
27016 	 * block descriptor.
27017 	 */
27018 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27019 
27020 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
27021 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
27022 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27023 		    "sr_change_blkmode: Mode Sense Failed\n");
27024 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27025 		return (rval);
27026 	}
27027 
27028 	/* Check the block descriptor len to handle only 1 block descriptor */
27029 	sense_mhp = (struct mode_header *)sense;
27030 	if ((sense_mhp->bdesc_length == 0) ||
27031 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
27032 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27033 		    "sr_change_blkmode: Mode Sense returned invalid block"
27034 		    " descriptor length\n");
27035 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27036 		return (EIO);
27037 	}
27038 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
27039 	current_bsize = ((sense_desc->blksize_hi << 16) |
27040 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
27041 
27042 	/* Process command */
27043 	switch (cmd) {
27044 	case CDROMGBLKMODE:
27045 		/* Return the block size obtained during the mode sense */
27046 		if (ddi_copyout(&current_bsize, (void *)data,
27047 		    sizeof (int), flag) != 0)
27048 			rval = EFAULT;
27049 		break;
27050 	case CDROMSBLKMODE:
27051 		/* Validate the requested block size */
27052 		switch (data) {
27053 		case CDROM_BLK_512:
27054 		case CDROM_BLK_1024:
27055 		case CDROM_BLK_2048:
27056 		case CDROM_BLK_2056:
27057 		case CDROM_BLK_2336:
27058 		case CDROM_BLK_2340:
27059 		case CDROM_BLK_2352:
27060 		case CDROM_BLK_2368:
27061 		case CDROM_BLK_2448:
27062 		case CDROM_BLK_2646:
27063 		case CDROM_BLK_2647:
27064 			break;
27065 		default:
27066 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27067 			    "sr_change_blkmode: "
27068 			    "Block Size '%ld' Not Supported\n", data);
27069 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27070 			return (EINVAL);
27071 		}
27072 
27073 		/*
27074 		 * The current block size matches the requested block size so
27075 		 * there is no need to send the mode select to change the size
27076 		 */
27077 		if (current_bsize == data) {
27078 			break;
27079 		}
27080 
27081 		/* Build the select data for the requested block size */
27082 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27083 		select_mhp = (struct mode_header *)select;
27084 		select_desc =
27085 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
27086 		/*
27087 		 * The LBA size is changed via the block descriptor, so the
27088 		 * descriptor is built according to the user data
27089 		 */
27090 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
27091 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
27092 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
27093 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
27094 
27095 		/* Send the mode select for the requested block size */
27096 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
27097 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27098 		    SD_PATH_STANDARD)) != 0) {
27099 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27100 			    "sr_change_blkmode: Mode Select Failed\n");
27101 			/*
27102 			 * The mode select failed for the requested block size,
27103 			 * so reset the data for the original block size and
27104 			 * send it to the target. The error is indicated by the
27105 			 * return value for the failed mode select.
27106 			 */
27107 			select_desc->blksize_hi  = sense_desc->blksize_hi;
27108 			select_desc->blksize_mid = sense_desc->blksize_mid;
27109 			select_desc->blksize_lo  = sense_desc->blksize_lo;
27110 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
27111 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27112 			    SD_PATH_STANDARD);
27113 		} else {
27114 			ASSERT(!mutex_owned(SD_MUTEX(un)));
27115 			mutex_enter(SD_MUTEX(un));
27116 			sd_update_block_info(un, (uint32_t)data, 0);
27117 
27118 			mutex_exit(SD_MUTEX(un));
27119 		}
27120 		break;
27121 	default:
27122 		/* should not reach here, but check anyway */
27123 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27124 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
27125 		rval = EINVAL;
27126 		break;
27127 	}
27128 
27129 	if (select) {
27130 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
27131 	}
27132 	if (sense) {
27133 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27134 	}
27135 	return (rval);
27136 }
27137 
27138 
27139 /*
27140  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
27141  * implement driver support for getting and setting the CD speed. The command
27142  * set used will be based on the device type. If the device has not been
27143  * identified as MMC the Toshiba vendor specific mode page will be used. If
27144  * the device is MMC but does not support the Real Time Streaming feature
27145  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
27146  * be used to read the speed.
27147  */
27148 
27149 /*
27150  *    Function: sr_change_speed()
27151  *
27152  * Description: This routine is the driver entry point for handling CD-ROM
27153  *		drive speed ioctl requests for devices supporting the Toshiba
27154  *		vendor specific drive speed mode page. Support for returning
27155  *		and changing the current drive speed in use by the device is
27156  *		implemented.
27157  *
27158  *   Arguments: dev - the device 'dev_t'
27159  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
27160  *		      CDROMSDRVSPEED (set)
27161  *		data - current drive speed or requested drive speed
27162  *		flag - this argument is a pass through to ddi_copyxxx() directly
27163  *		       from the mode argument of ioctl().
27164  *
27165  * Return Code: the code returned by sd_send_scsi_cmd()
27166  *		EINVAL if invalid arguments are provided
27167  *		EFAULT if ddi_copyxxx() fails
27168  *		ENXIO if fail ddi_get_soft_state
27169  *		EIO if invalid mode sense block descriptor length
27170  */
27171 
27172 static int
27173 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27174 {
27175 	struct sd_lun			*un = NULL;
27176 	struct mode_header		*sense_mhp, *select_mhp;
27177 	struct mode_speed		*sense_page, *select_page;
27178 	int				current_speed;
27179 	int				rval = EINVAL;
27180 	int				bd_len;
27181 	uchar_t				*sense = NULL;
27182 	uchar_t				*select = NULL;
27183 
27184 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27185 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27186 		return (ENXIO);
27187 	}
27188 
27189 	/*
27190 	 * Note: The drive speed is being modified here according to a Toshiba
27191 	 * vendor specific mode page (0x31).
27192 	 */
27193 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27194 
27195 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
27196 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
27197 	    SD_PATH_STANDARD)) != 0) {
27198 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27199 		    "sr_change_speed: Mode Sense Failed\n");
27200 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27201 		return (rval);
27202 	}
27203 	sense_mhp  = (struct mode_header *)sense;
27204 
27205 	/* Check the block descriptor len to handle only 1 block descriptor */
27206 	bd_len = sense_mhp->bdesc_length;
27207 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27208 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27209 		    "sr_change_speed: Mode Sense returned invalid block "
27210 		    "descriptor length\n");
27211 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27212 		return (EIO);
27213 	}
27214 
27215 	sense_page = (struct mode_speed *)
27216 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27217 	current_speed = sense_page->speed;
27218 
27219 	/* Process command */
27220 	switch (cmd) {
27221 	case CDROMGDRVSPEED:
27222 		/* Return the drive speed obtained during the mode sense */
27223 		if (current_speed == 0x2) {
27224 			current_speed = CDROM_TWELVE_SPEED;
27225 		}
27226 		if (ddi_copyout(&current_speed, (void *)data,
27227 		    sizeof (int), flag) != 0) {
27228 			rval = EFAULT;
27229 		}
27230 		break;
27231 	case CDROMSDRVSPEED:
27232 		/* Validate the requested drive speed */
27233 		switch ((uchar_t)data) {
27234 		case CDROM_TWELVE_SPEED:
27235 			data = 0x2;
27236 			/*FALLTHROUGH*/
27237 		case CDROM_NORMAL_SPEED:
27238 		case CDROM_DOUBLE_SPEED:
27239 		case CDROM_QUAD_SPEED:
27240 		case CDROM_MAXIMUM_SPEED:
27241 			break;
27242 		default:
27243 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27244 			    "sr_change_speed: "
27245 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
27246 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27247 			return (EINVAL);
27248 		}
27249 
27250 		/*
27251 		 * The current drive speed matches the requested drive speed so
27252 		 * there is no need to send the mode select to change the speed
27253 		 */
27254 		if (current_speed == data) {
27255 			break;
27256 		}
27257 
27258 		/* Build the select data for the requested drive speed */
27259 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27260 		select_mhp = (struct mode_header *)select;
27261 		select_mhp->bdesc_length = 0;
27262 		select_page =
27263 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27264 		select_page =
27265 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27266 		select_page->mode_page.code = CDROM_MODE_SPEED;
27267 		select_page->mode_page.length = 2;
27268 		select_page->speed = (uchar_t)data;
27269 
27270 		/* Send the mode select for the requested block size */
27271 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
27272 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27273 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
27274 			/*
27275 			 * The mode select failed for the requested drive speed,
27276 			 * so reset the data for the original drive speed and
27277 			 * send it to the target. The error is indicated by the
27278 			 * return value for the failed mode select.
27279 			 */
27280 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27281 			    "sr_drive_speed: Mode Select Failed\n");
27282 			select_page->speed = sense_page->speed;
27283 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
27284 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27285 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27286 		}
27287 		break;
27288 	default:
27289 		/* should not reach here, but check anyway */
27290 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27291 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
27292 		rval = EINVAL;
27293 		break;
27294 	}
27295 
27296 	if (select) {
27297 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
27298 	}
27299 	if (sense) {
27300 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27301 	}
27302 
27303 	return (rval);
27304 }
27305 
27306 
27307 /*
27308  *    Function: sr_atapi_change_speed()
27309  *
27310  * Description: This routine is the driver entry point for handling CD-ROM
27311  *		drive speed ioctl requests for MMC devices that do not support
27312  *		the Real Time Streaming feature (0x107).
27313  *
27314  *		Note: This routine will use the SET SPEED command which may not
27315  *		be supported by all devices.
27316  *
27317  *   Arguments: dev- the device 'dev_t'
27318  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
27319  *		     CDROMSDRVSPEED (set)
27320  *		data- current drive speed or requested drive speed
27321  *		flag- this argument is a pass through to ddi_copyxxx() directly
27322  *		      from the mode argument of ioctl().
27323  *
27324  * Return Code: the code returned by sd_send_scsi_cmd()
27325  *		EINVAL if invalid arguments are provided
27326  *		EFAULT if ddi_copyxxx() fails
27327  *		ENXIO if fail ddi_get_soft_state
27328  *		EIO if invalid mode sense block descriptor length
27329  */
27330 
27331 static int
27332 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27333 {
27334 	struct sd_lun			*un;
27335 	struct uscsi_cmd		*com = NULL;
27336 	struct mode_header_grp2		*sense_mhp;
27337 	uchar_t				*sense_page;
27338 	uchar_t				*sense = NULL;
27339 	char				cdb[CDB_GROUP5];
27340 	int				bd_len;
27341 	int				current_speed = 0;
27342 	int				max_speed = 0;
27343 	int				rval;
27344 
27345 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27346 
27347 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27348 		return (ENXIO);
27349 	}
27350 
27351 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
27352 
27353 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
27354 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
27355 	    SD_PATH_STANDARD)) != 0) {
27356 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27357 		    "sr_atapi_change_speed: Mode Sense Failed\n");
27358 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27359 		return (rval);
27360 	}
27361 
27362 	/* Check the block descriptor len to handle only 1 block descriptor */
27363 	sense_mhp = (struct mode_header_grp2 *)sense;
27364 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
27365 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27366 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27367 		    "sr_atapi_change_speed: Mode Sense returned invalid "
27368 		    "block descriptor length\n");
27369 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27370 		return (EIO);
27371 	}
27372 
27373 	/* Calculate the current and maximum drive speeds */
27374 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27375 	current_speed = (sense_page[14] << 8) | sense_page[15];
27376 	max_speed = (sense_page[8] << 8) | sense_page[9];
27377 
27378 	/* Process the command */
27379 	switch (cmd) {
27380 	case CDROMGDRVSPEED:
27381 		current_speed /= SD_SPEED_1X;
27382 		if (ddi_copyout(&current_speed, (void *)data,
27383 		    sizeof (int), flag) != 0)
27384 			rval = EFAULT;
27385 		break;
27386 	case CDROMSDRVSPEED:
27387 		/* Convert the speed code to KB/sec */
27388 		switch ((uchar_t)data) {
27389 		case CDROM_NORMAL_SPEED:
27390 			current_speed = SD_SPEED_1X;
27391 			break;
27392 		case CDROM_DOUBLE_SPEED:
27393 			current_speed = 2 * SD_SPEED_1X;
27394 			break;
27395 		case CDROM_QUAD_SPEED:
27396 			current_speed = 4 * SD_SPEED_1X;
27397 			break;
27398 		case CDROM_TWELVE_SPEED:
27399 			current_speed = 12 * SD_SPEED_1X;
27400 			break;
27401 		case CDROM_MAXIMUM_SPEED:
27402 			current_speed = 0xffff;
27403 			break;
27404 		default:
27405 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27406 			    "sr_atapi_change_speed: invalid drive speed %d\n",
27407 			    (uchar_t)data);
27408 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27409 			return (EINVAL);
27410 		}
27411 
27412 		/* Check the request against the drive's max speed. */
27413 		if (current_speed != 0xffff) {
27414 			if (current_speed > max_speed) {
27415 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27416 				return (EINVAL);
27417 			}
27418 		}
27419 
27420 		/*
27421 		 * Build and send the SET SPEED command
27422 		 *
27423 		 * Note: The SET SPEED (0xBB) command used in this routine is
27424 		 * obsolete per the SCSI MMC spec but still supported in the
27425 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27426 		 * therefore the command is still implemented in this routine.
27427 		 */
27428 		bzero(cdb, sizeof (cdb));
27429 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
27430 		cdb[2] = (uchar_t)(current_speed >> 8);
27431 		cdb[3] = (uchar_t)current_speed;
27432 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27433 		com->uscsi_cdb	   = (caddr_t)cdb;
27434 		com->uscsi_cdblen  = CDB_GROUP5;
27435 		com->uscsi_bufaddr = NULL;
27436 		com->uscsi_buflen  = 0;
27437 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
27438 		rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, 0,
27439 		    UIO_SYSSPACE, SD_PATH_STANDARD);
27440 		break;
27441 	default:
27442 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27443 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27444 		rval = EINVAL;
27445 	}
27446 
27447 	if (sense) {
27448 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27449 	}
27450 	if (com) {
27451 		kmem_free(com, sizeof (*com));
27452 	}
27453 	return (rval);
27454 }
27455 
27456 
27457 /*
27458  *    Function: sr_pause_resume()
27459  *
27460  * Description: This routine is the driver entry point for handling CD-ROM
27461  *		pause/resume ioctl requests. This only affects the audio play
27462  *		operation.
27463  *
27464  *   Arguments: dev - the device 'dev_t'
27465  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27466  *		      for setting the resume bit of the cdb.
27467  *
27468  * Return Code: the code returned by sd_send_scsi_cmd()
27469  *		EINVAL if invalid mode specified
27470  *
27471  */
27472 
27473 static int
27474 sr_pause_resume(dev_t dev, int cmd)
27475 {
27476 	struct sd_lun		*un;
27477 	struct uscsi_cmd	*com;
27478 	char			cdb[CDB_GROUP1];
27479 	int			rval;
27480 
27481 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27482 		return (ENXIO);
27483 	}
27484 
27485 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27486 	bzero(cdb, CDB_GROUP1);
27487 	cdb[0] = SCMD_PAUSE_RESUME;
27488 	switch (cmd) {
27489 	case CDROMRESUME:
27490 		cdb[8] = 1;
27491 		break;
27492 	case CDROMPAUSE:
27493 		cdb[8] = 0;
27494 		break;
27495 	default:
27496 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27497 		    " Command '%x' Not Supported\n", cmd);
27498 		rval = EINVAL;
27499 		goto done;
27500 	}
27501 
27502 	com->uscsi_cdb    = cdb;
27503 	com->uscsi_cdblen = CDB_GROUP1;
27504 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27505 
27506 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27507 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27508 
27509 done:
27510 	kmem_free(com, sizeof (*com));
27511 	return (rval);
27512 }
27513 
27514 
27515 /*
27516  *    Function: sr_play_msf()
27517  *
27518  * Description: This routine is the driver entry point for handling CD-ROM
27519  *		ioctl requests to output the audio signals at the specified
27520  *		starting address and continue the audio play until the specified
27521  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27522  *		Frame (MSF) format.
27523  *
27524  *   Arguments: dev	- the device 'dev_t'
27525  *		data	- pointer to user provided audio msf structure,
27526  *		          specifying start/end addresses.
27527  *		flag	- this argument is a pass through to ddi_copyxxx()
27528  *		          directly from the mode argument of ioctl().
27529  *
27530  * Return Code: the code returned by sd_send_scsi_cmd()
27531  *		EFAULT if ddi_copyxxx() fails
27532  *		ENXIO if fail ddi_get_soft_state
27533  *		EINVAL if data pointer is NULL
27534  */
27535 
27536 static int
27537 sr_play_msf(dev_t dev, caddr_t data, int flag)
27538 {
27539 	struct sd_lun		*un;
27540 	struct uscsi_cmd	*com;
27541 	struct cdrom_msf	msf_struct;
27542 	struct cdrom_msf	*msf = &msf_struct;
27543 	char			cdb[CDB_GROUP1];
27544 	int			rval;
27545 
27546 	if (data == NULL) {
27547 		return (EINVAL);
27548 	}
27549 
27550 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27551 		return (ENXIO);
27552 	}
27553 
27554 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27555 		return (EFAULT);
27556 	}
27557 
27558 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27559 	bzero(cdb, CDB_GROUP1);
27560 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27561 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27562 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27563 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27564 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27565 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27566 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27567 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27568 	} else {
27569 		cdb[3] = msf->cdmsf_min0;
27570 		cdb[4] = msf->cdmsf_sec0;
27571 		cdb[5] = msf->cdmsf_frame0;
27572 		cdb[6] = msf->cdmsf_min1;
27573 		cdb[7] = msf->cdmsf_sec1;
27574 		cdb[8] = msf->cdmsf_frame1;
27575 	}
27576 	com->uscsi_cdb    = cdb;
27577 	com->uscsi_cdblen = CDB_GROUP1;
27578 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27579 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27580 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27581 	kmem_free(com, sizeof (*com));
27582 	return (rval);
27583 }
27584 
27585 
27586 /*
27587  *    Function: sr_play_trkind()
27588  *
27589  * Description: This routine is the driver entry point for handling CD-ROM
27590  *		ioctl requests to output the audio signals at the specified
27591  *		starting address and continue the audio play until the specified
27592  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27593  *		format.
27594  *
27595  *   Arguments: dev	- the device 'dev_t'
27596  *		data	- pointer to user provided audio track/index structure,
27597  *		          specifying start/end addresses.
27598  *		flag	- this argument is a pass through to ddi_copyxxx()
27599  *		          directly from the mode argument of ioctl().
27600  *
27601  * Return Code: the code returned by sd_send_scsi_cmd()
27602  *		EFAULT if ddi_copyxxx() fails
27603  *		ENXIO if fail ddi_get_soft_state
27604  *		EINVAL if data pointer is NULL
27605  */
27606 
27607 static int
27608 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27609 {
27610 	struct cdrom_ti		ti_struct;
27611 	struct cdrom_ti		*ti = &ti_struct;
27612 	struct uscsi_cmd	*com = NULL;
27613 	char			cdb[CDB_GROUP1];
27614 	int			rval;
27615 
27616 	if (data == NULL) {
27617 		return (EINVAL);
27618 	}
27619 
27620 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27621 		return (EFAULT);
27622 	}
27623 
27624 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27625 	bzero(cdb, CDB_GROUP1);
27626 	cdb[0] = SCMD_PLAYAUDIO_TI;
27627 	cdb[4] = ti->cdti_trk0;
27628 	cdb[5] = ti->cdti_ind0;
27629 	cdb[7] = ti->cdti_trk1;
27630 	cdb[8] = ti->cdti_ind1;
27631 	com->uscsi_cdb    = cdb;
27632 	com->uscsi_cdblen = CDB_GROUP1;
27633 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27634 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27635 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27636 	kmem_free(com, sizeof (*com));
27637 	return (rval);
27638 }
27639 
27640 
27641 /*
27642  *    Function: sr_read_all_subcodes()
27643  *
27644  * Description: This routine is the driver entry point for handling CD-ROM
27645  *		ioctl requests to return raw subcode data while the target is
27646  *		playing audio (CDROMSUBCODE).
27647  *
27648  *   Arguments: dev	- the device 'dev_t'
27649  *		data	- pointer to user provided cdrom subcode structure,
27650  *		          specifying the transfer length and address.
27651  *		flag	- this argument is a pass through to ddi_copyxxx()
27652  *		          directly from the mode argument of ioctl().
27653  *
27654  * Return Code: the code returned by sd_send_scsi_cmd()
27655  *		EFAULT if ddi_copyxxx() fails
27656  *		ENXIO if fail ddi_get_soft_state
27657  *		EINVAL if data pointer is NULL
27658  */
27659 
27660 static int
27661 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27662 {
27663 	struct sd_lun		*un = NULL;
27664 	struct uscsi_cmd	*com = NULL;
27665 	struct cdrom_subcode	*subcode = NULL;
27666 	int			rval;
27667 	size_t			buflen;
27668 	char			cdb[CDB_GROUP5];
27669 
27670 #ifdef _MULTI_DATAMODEL
27671 	/* To support ILP32 applications in an LP64 world */
27672 	struct cdrom_subcode32		cdrom_subcode32;
27673 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27674 #endif
27675 	if (data == NULL) {
27676 		return (EINVAL);
27677 	}
27678 
27679 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27680 		return (ENXIO);
27681 	}
27682 
27683 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27684 
27685 #ifdef _MULTI_DATAMODEL
27686 	switch (ddi_model_convert_from(flag & FMODELS)) {
27687 	case DDI_MODEL_ILP32:
27688 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27689 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27690 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27691 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27692 			return (EFAULT);
27693 		}
27694 		/* Convert the ILP32 uscsi data from the application to LP64 */
27695 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27696 		break;
27697 	case DDI_MODEL_NONE:
27698 		if (ddi_copyin(data, subcode,
27699 		    sizeof (struct cdrom_subcode), flag)) {
27700 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27701 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27702 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27703 			return (EFAULT);
27704 		}
27705 		break;
27706 	}
27707 #else /* ! _MULTI_DATAMODEL */
27708 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27709 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27710 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27711 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27712 		return (EFAULT);
27713 	}
27714 #endif /* _MULTI_DATAMODEL */
27715 
27716 	/*
27717 	 * Since MMC-2 expects max 3 bytes for length, check if the
27718 	 * length input is greater than 3 bytes
27719 	 */
27720 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27721 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27722 		    "sr_read_all_subcodes: "
27723 		    "cdrom transfer length too large: %d (limit %d)\n",
27724 		    subcode->cdsc_length, 0xFFFFFF);
27725 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27726 		return (EINVAL);
27727 	}
27728 
27729 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27730 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27731 	bzero(cdb, CDB_GROUP5);
27732 
27733 	if (un->un_f_mmc_cap == TRUE) {
27734 		cdb[0] = (char)SCMD_READ_CD;
27735 		cdb[2] = (char)0xff;
27736 		cdb[3] = (char)0xff;
27737 		cdb[4] = (char)0xff;
27738 		cdb[5] = (char)0xff;
27739 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27740 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27741 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27742 		cdb[10] = 1;
27743 	} else {
27744 		/*
27745 		 * Note: A vendor specific command (0xDF) is being used her to
27746 		 * request a read of all subcodes.
27747 		 */
27748 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27749 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27750 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27751 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27752 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
27753 	}
27754 	com->uscsi_cdb	   = cdb;
27755 	com->uscsi_cdblen  = CDB_GROUP5;
27756 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
27757 	com->uscsi_buflen  = buflen;
27758 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27759 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_USERSPACE,
27760 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27761 	kmem_free(subcode, sizeof (struct cdrom_subcode));
27762 	kmem_free(com, sizeof (*com));
27763 	return (rval);
27764 }
27765 
27766 
27767 /*
27768  *    Function: sr_read_subchannel()
27769  *
27770  * Description: This routine is the driver entry point for handling CD-ROM
27771  *		ioctl requests to return the Q sub-channel data of the CD
27772  *		current position block. (CDROMSUBCHNL) The data includes the
27773  *		track number, index number, absolute CD-ROM address (LBA or MSF
27774  *		format per the user) , track relative CD-ROM address (LBA or MSF
27775  *		format per the user), control data and audio status.
27776  *
27777  *   Arguments: dev	- the device 'dev_t'
27778  *		data	- pointer to user provided cdrom sub-channel structure
27779  *		flag	- this argument is a pass through to ddi_copyxxx()
27780  *		          directly from the mode argument of ioctl().
27781  *
27782  * Return Code: the code returned by sd_send_scsi_cmd()
27783  *		EFAULT if ddi_copyxxx() fails
27784  *		ENXIO if fail ddi_get_soft_state
27785  *		EINVAL if data pointer is NULL
27786  */
27787 
27788 static int
27789 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
27790 {
27791 	struct sd_lun		*un;
27792 	struct uscsi_cmd	*com;
27793 	struct cdrom_subchnl	subchanel;
27794 	struct cdrom_subchnl	*subchnl = &subchanel;
27795 	char			cdb[CDB_GROUP1];
27796 	caddr_t			buffer;
27797 	int			rval;
27798 
27799 	if (data == NULL) {
27800 		return (EINVAL);
27801 	}
27802 
27803 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27804 	    (un->un_state == SD_STATE_OFFLINE)) {
27805 		return (ENXIO);
27806 	}
27807 
27808 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
27809 		return (EFAULT);
27810 	}
27811 
27812 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
27813 	bzero(cdb, CDB_GROUP1);
27814 	cdb[0] = SCMD_READ_SUBCHANNEL;
27815 	/* Set the MSF bit based on the user requested address format */
27816 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
27817 	/*
27818 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
27819 	 * returned
27820 	 */
27821 	cdb[2] = 0x40;
27822 	/*
27823 	 * Set byte 3 to specify the return data format. A value of 0x01
27824 	 * indicates that the CD-ROM current position should be returned.
27825 	 */
27826 	cdb[3] = 0x01;
27827 	cdb[8] = 0x10;
27828 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27829 	com->uscsi_cdb	   = cdb;
27830 	com->uscsi_cdblen  = CDB_GROUP1;
27831 	com->uscsi_bufaddr = buffer;
27832 	com->uscsi_buflen  = 16;
27833 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27834 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27835 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27836 	if (rval != 0) {
27837 		kmem_free(buffer, 16);
27838 		kmem_free(com, sizeof (*com));
27839 		return (rval);
27840 	}
27841 
27842 	/* Process the returned Q sub-channel data */
27843 	subchnl->cdsc_audiostatus = buffer[1];
27844 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
27845 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
27846 	subchnl->cdsc_trk	= buffer[6];
27847 	subchnl->cdsc_ind	= buffer[7];
27848 	if (subchnl->cdsc_format & CDROM_LBA) {
27849 		subchnl->cdsc_absaddr.lba =
27850 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27851 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27852 		subchnl->cdsc_reladdr.lba =
27853 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
27854 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
27855 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
27856 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
27857 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
27858 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
27859 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
27860 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
27861 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
27862 	} else {
27863 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
27864 		subchnl->cdsc_absaddr.msf.second = buffer[10];
27865 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
27866 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
27867 		subchnl->cdsc_reladdr.msf.second = buffer[14];
27868 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
27869 	}
27870 	kmem_free(buffer, 16);
27871 	kmem_free(com, sizeof (*com));
27872 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
27873 	    != 0) {
27874 		return (EFAULT);
27875 	}
27876 	return (rval);
27877 }
27878 
27879 
27880 /*
27881  *    Function: sr_read_tocentry()
27882  *
27883  * Description: This routine is the driver entry point for handling CD-ROM
27884  *		ioctl requests to read from the Table of Contents (TOC)
27885  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
27886  *		fields, the starting address (LBA or MSF format per the user)
27887  *		and the data mode if the user specified track is a data track.
27888  *
27889  *		Note: The READ HEADER (0x44) command used in this routine is
27890  *		obsolete per the SCSI MMC spec but still supported in the
27891  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27892  *		therefore the command is still implemented in this routine.
27893  *
27894  *   Arguments: dev	- the device 'dev_t'
27895  *		data	- pointer to user provided toc entry structure,
27896  *			  specifying the track # and the address format
27897  *			  (LBA or MSF).
27898  *		flag	- this argument is a pass through to ddi_copyxxx()
27899  *		          directly from the mode argument of ioctl().
27900  *
27901  * Return Code: the code returned by sd_send_scsi_cmd()
27902  *		EFAULT if ddi_copyxxx() fails
27903  *		ENXIO if fail ddi_get_soft_state
27904  *		EINVAL if data pointer is NULL
27905  */
27906 
27907 static int
27908 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
27909 {
27910 	struct sd_lun		*un = NULL;
27911 	struct uscsi_cmd	*com;
27912 	struct cdrom_tocentry	toc_entry;
27913 	struct cdrom_tocentry	*entry = &toc_entry;
27914 	caddr_t			buffer;
27915 	int			rval;
27916 	char			cdb[CDB_GROUP1];
27917 
27918 	if (data == NULL) {
27919 		return (EINVAL);
27920 	}
27921 
27922 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27923 	    (un->un_state == SD_STATE_OFFLINE)) {
27924 		return (ENXIO);
27925 	}
27926 
27927 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
27928 		return (EFAULT);
27929 	}
27930 
27931 	/* Validate the requested track and address format */
27932 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
27933 		return (EINVAL);
27934 	}
27935 
27936 	if (entry->cdte_track == 0) {
27937 		return (EINVAL);
27938 	}
27939 
27940 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
27941 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27942 	bzero(cdb, CDB_GROUP1);
27943 
27944 	cdb[0] = SCMD_READ_TOC;
27945 	/* Set the MSF bit based on the user requested address format  */
27946 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
27947 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27948 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
27949 	} else {
27950 		cdb[6] = entry->cdte_track;
27951 	}
27952 
27953 	/*
27954 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27955 	 * (4 byte TOC response header + 8 byte track descriptor)
27956 	 */
27957 	cdb[8] = 12;
27958 	com->uscsi_cdb	   = cdb;
27959 	com->uscsi_cdblen  = CDB_GROUP1;
27960 	com->uscsi_bufaddr = buffer;
27961 	com->uscsi_buflen  = 0x0C;
27962 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
27963 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27964 	    UIO_SYSSPACE, SD_PATH_STANDARD);
27965 	if (rval != 0) {
27966 		kmem_free(buffer, 12);
27967 		kmem_free(com, sizeof (*com));
27968 		return (rval);
27969 	}
27970 
27971 	/* Process the toc entry */
27972 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
27973 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
27974 	if (entry->cdte_format & CDROM_LBA) {
27975 		entry->cdte_addr.lba =
27976 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27977 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27978 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
27979 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
27980 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
27981 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
27982 		/*
27983 		 * Send a READ TOC command using the LBA address format to get
27984 		 * the LBA for the track requested so it can be used in the
27985 		 * READ HEADER request
27986 		 *
27987 		 * Note: The MSF bit of the READ HEADER command specifies the
27988 		 * output format. The block address specified in that command
27989 		 * must be in LBA format.
27990 		 */
27991 		cdb[1] = 0;
27992 		rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
27993 		    UIO_SYSSPACE, SD_PATH_STANDARD);
27994 		if (rval != 0) {
27995 			kmem_free(buffer, 12);
27996 			kmem_free(com, sizeof (*com));
27997 			return (rval);
27998 		}
27999 	} else {
28000 		entry->cdte_addr.msf.minute	= buffer[9];
28001 		entry->cdte_addr.msf.second	= buffer[10];
28002 		entry->cdte_addr.msf.frame	= buffer[11];
28003 		/*
28004 		 * Send a READ TOC command using the LBA address format to get
28005 		 * the LBA for the track requested so it can be used in the
28006 		 * READ HEADER request
28007 		 *
28008 		 * Note: The MSF bit of the READ HEADER command specifies the
28009 		 * output format. The block address specified in that command
28010 		 * must be in LBA format.
28011 		 */
28012 		cdb[1] = 0;
28013 		rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
28014 		    UIO_SYSSPACE, SD_PATH_STANDARD);
28015 		if (rval != 0) {
28016 			kmem_free(buffer, 12);
28017 			kmem_free(com, sizeof (*com));
28018 			return (rval);
28019 		}
28020 	}
28021 
28022 	/*
28023 	 * Build and send the READ HEADER command to determine the data mode of
28024 	 * the user specified track.
28025 	 */
28026 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
28027 	    (entry->cdte_track != CDROM_LEADOUT)) {
28028 		bzero(cdb, CDB_GROUP1);
28029 		cdb[0] = SCMD_READ_HEADER;
28030 		cdb[2] = buffer[8];
28031 		cdb[3] = buffer[9];
28032 		cdb[4] = buffer[10];
28033 		cdb[5] = buffer[11];
28034 		cdb[8] = 0x08;
28035 		com->uscsi_buflen = 0x08;
28036 		rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
28037 		    UIO_SYSSPACE, SD_PATH_STANDARD);
28038 		if (rval == 0) {
28039 			entry->cdte_datamode = buffer[0];
28040 		} else {
28041 			/*
28042 			 * READ HEADER command failed, since this is
28043 			 * obsoleted in one spec, its better to return
28044 			 * -1 for an invlid track so that we can still
28045 			 * recieve the rest of the TOC data.
28046 			 */
28047 			entry->cdte_datamode = (uchar_t)-1;
28048 		}
28049 	} else {
28050 		entry->cdte_datamode = (uchar_t)-1;
28051 	}
28052 
28053 	kmem_free(buffer, 12);
28054 	kmem_free(com, sizeof (*com));
28055 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
28056 		return (EFAULT);
28057 
28058 	return (rval);
28059 }
28060 
28061 
28062 /*
28063  *    Function: sr_read_tochdr()
28064  *
28065  * Description: This routine is the driver entry point for handling CD-ROM
28066  * 		ioctl requests to read the Table of Contents (TOC) header
28067  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
28068  *		and ending track numbers
28069  *
28070  *   Arguments: dev	- the device 'dev_t'
28071  *		data	- pointer to user provided toc header structure,
28072  *			  specifying the starting and ending track numbers.
28073  *		flag	- this argument is a pass through to ddi_copyxxx()
28074  *			  directly from the mode argument of ioctl().
28075  *
28076  * Return Code: the code returned by sd_send_scsi_cmd()
28077  *		EFAULT if ddi_copyxxx() fails
28078  *		ENXIO if fail ddi_get_soft_state
28079  *		EINVAL if data pointer is NULL
28080  */
28081 
28082 static int
28083 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
28084 {
28085 	struct sd_lun		*un;
28086 	struct uscsi_cmd	*com;
28087 	struct cdrom_tochdr	toc_header;
28088 	struct cdrom_tochdr	*hdr = &toc_header;
28089 	char			cdb[CDB_GROUP1];
28090 	int			rval;
28091 	caddr_t			buffer;
28092 
28093 	if (data == NULL) {
28094 		return (EINVAL);
28095 	}
28096 
28097 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28098 	    (un->un_state == SD_STATE_OFFLINE)) {
28099 		return (ENXIO);
28100 	}
28101 
28102 	buffer = kmem_zalloc(4, KM_SLEEP);
28103 	bzero(cdb, CDB_GROUP1);
28104 	cdb[0] = SCMD_READ_TOC;
28105 	/*
28106 	 * Specifying a track number of 0x00 in the READ TOC command indicates
28107 	 * that the TOC header should be returned
28108 	 */
28109 	cdb[6] = 0x00;
28110 	/*
28111 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
28112 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
28113 	 */
28114 	cdb[8] = 0x04;
28115 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28116 	com->uscsi_cdb	   = cdb;
28117 	com->uscsi_cdblen  = CDB_GROUP1;
28118 	com->uscsi_bufaddr = buffer;
28119 	com->uscsi_buflen  = 0x04;
28120 	com->uscsi_timeout = 300;
28121 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28122 
28123 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
28124 	    UIO_SYSSPACE, SD_PATH_STANDARD);
28125 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28126 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
28127 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
28128 	} else {
28129 		hdr->cdth_trk0 = buffer[2];
28130 		hdr->cdth_trk1 = buffer[3];
28131 	}
28132 	kmem_free(buffer, 4);
28133 	kmem_free(com, sizeof (*com));
28134 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
28135 		return (EFAULT);
28136 	}
28137 	return (rval);
28138 }
28139 
28140 
28141 /*
28142  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
28143  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
28144  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
28145  * digital audio and extended architecture digital audio. These modes are
28146  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
28147  * MMC specs.
28148  *
28149  * In addition to support for the various data formats these routines also
28150  * include support for devices that implement only the direct access READ
28151  * commands (0x08, 0x28), devices that implement the READ_CD commands
28152  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
28153  * READ CDXA commands (0xD8, 0xDB)
28154  */
28155 
28156 /*
28157  *    Function: sr_read_mode1()
28158  *
28159  * Description: This routine is the driver entry point for handling CD-ROM
28160  *		ioctl read mode1 requests (CDROMREADMODE1).
28161  *
28162  *   Arguments: dev	- the device 'dev_t'
28163  *		data	- pointer to user provided cd read structure specifying
28164  *			  the lba buffer address and length.
28165  *		flag	- this argument is a pass through to ddi_copyxxx()
28166  *			  directly from the mode argument of ioctl().
28167  *
28168  * Return Code: the code returned by sd_send_scsi_cmd()
28169  *		EFAULT if ddi_copyxxx() fails
28170  *		ENXIO if fail ddi_get_soft_state
28171  *		EINVAL if data pointer is NULL
28172  */
28173 
28174 static int
28175 sr_read_mode1(dev_t dev, caddr_t data, int flag)
28176 {
28177 	struct sd_lun		*un;
28178 	struct cdrom_read	mode1_struct;
28179 	struct cdrom_read	*mode1 = &mode1_struct;
28180 	int			rval;
28181 #ifdef _MULTI_DATAMODEL
28182 	/* To support ILP32 applications in an LP64 world */
28183 	struct cdrom_read32	cdrom_read32;
28184 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28185 #endif /* _MULTI_DATAMODEL */
28186 
28187 	if (data == NULL) {
28188 		return (EINVAL);
28189 	}
28190 
28191 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28192 	    (un->un_state == SD_STATE_OFFLINE)) {
28193 		return (ENXIO);
28194 	}
28195 
28196 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28197 	    "sd_read_mode1: entry: un:0x%p\n", un);
28198 
28199 #ifdef _MULTI_DATAMODEL
28200 	switch (ddi_model_convert_from(flag & FMODELS)) {
28201 	case DDI_MODEL_ILP32:
28202 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28203 			return (EFAULT);
28204 		}
28205 		/* Convert the ILP32 uscsi data from the application to LP64 */
28206 		cdrom_read32tocdrom_read(cdrd32, mode1);
28207 		break;
28208 	case DDI_MODEL_NONE:
28209 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28210 			return (EFAULT);
28211 		}
28212 	}
28213 #else /* ! _MULTI_DATAMODEL */
28214 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28215 		return (EFAULT);
28216 	}
28217 #endif /* _MULTI_DATAMODEL */
28218 
28219 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
28220 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
28221 
28222 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28223 	    "sd_read_mode1: exit: un:0x%p\n", un);
28224 
28225 	return (rval);
28226 }
28227 
28228 
28229 /*
28230  *    Function: sr_read_cd_mode2()
28231  *
28232  * Description: This routine is the driver entry point for handling CD-ROM
28233  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28234  *		support the READ CD (0xBE) command or the 1st generation
28235  *		READ CD (0xD4) command.
28236  *
28237  *   Arguments: dev	- the device 'dev_t'
28238  *		data	- pointer to user provided cd read structure specifying
28239  *			  the lba buffer address and length.
28240  *		flag	- this argument is a pass through to ddi_copyxxx()
28241  *			  directly from the mode argument of ioctl().
28242  *
28243  * Return Code: the code returned by sd_send_scsi_cmd()
28244  *		EFAULT if ddi_copyxxx() fails
28245  *		ENXIO if fail ddi_get_soft_state
28246  *		EINVAL if data pointer is NULL
28247  */
28248 
28249 static int
28250 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
28251 {
28252 	struct sd_lun		*un;
28253 	struct uscsi_cmd	*com;
28254 	struct cdrom_read	mode2_struct;
28255 	struct cdrom_read	*mode2 = &mode2_struct;
28256 	uchar_t			cdb[CDB_GROUP5];
28257 	int			nblocks;
28258 	int			rval;
28259 #ifdef _MULTI_DATAMODEL
28260 	/*  To support ILP32 applications in an LP64 world */
28261 	struct cdrom_read32	cdrom_read32;
28262 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28263 #endif /* _MULTI_DATAMODEL */
28264 
28265 	if (data == NULL) {
28266 		return (EINVAL);
28267 	}
28268 
28269 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28270 	    (un->un_state == SD_STATE_OFFLINE)) {
28271 		return (ENXIO);
28272 	}
28273 
28274 #ifdef _MULTI_DATAMODEL
28275 	switch (ddi_model_convert_from(flag & FMODELS)) {
28276 	case DDI_MODEL_ILP32:
28277 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28278 			return (EFAULT);
28279 		}
28280 		/* Convert the ILP32 uscsi data from the application to LP64 */
28281 		cdrom_read32tocdrom_read(cdrd32, mode2);
28282 		break;
28283 	case DDI_MODEL_NONE:
28284 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28285 			return (EFAULT);
28286 		}
28287 		break;
28288 	}
28289 
28290 #else /* ! _MULTI_DATAMODEL */
28291 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28292 		return (EFAULT);
28293 	}
28294 #endif /* _MULTI_DATAMODEL */
28295 
28296 	bzero(cdb, sizeof (cdb));
28297 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
28298 		/* Read command supported by 1st generation atapi drives */
28299 		cdb[0] = SCMD_READ_CDD4;
28300 	} else {
28301 		/* Universal CD Access Command */
28302 		cdb[0] = SCMD_READ_CD;
28303 	}
28304 
28305 	/*
28306 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
28307 	 */
28308 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
28309 
28310 	/* set the start address */
28311 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
28312 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
28313 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28314 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
28315 
28316 	/* set the transfer length */
28317 	nblocks = mode2->cdread_buflen / 2336;
28318 	cdb[6] = (uchar_t)(nblocks >> 16);
28319 	cdb[7] = (uchar_t)(nblocks >> 8);
28320 	cdb[8] = (uchar_t)nblocks;
28321 
28322 	/* set the filter bits */
28323 	cdb[9] = CDROM_READ_CD_USERDATA;
28324 
28325 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28326 	com->uscsi_cdb = (caddr_t)cdb;
28327 	com->uscsi_cdblen = sizeof (cdb);
28328 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28329 	com->uscsi_buflen = mode2->cdread_buflen;
28330 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28331 
28332 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_USERSPACE,
28333 	    UIO_SYSSPACE, SD_PATH_STANDARD);
28334 	kmem_free(com, sizeof (*com));
28335 	return (rval);
28336 }
28337 
28338 
28339 /*
28340  *    Function: sr_read_mode2()
28341  *
28342  * Description: This routine is the driver entry point for handling CD-ROM
28343  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28344  *		do not support the READ CD (0xBE) command.
28345  *
28346  *   Arguments: dev	- the device 'dev_t'
28347  *		data	- pointer to user provided cd read structure specifying
28348  *			  the lba buffer address and length.
28349  *		flag	- this argument is a pass through to ddi_copyxxx()
28350  *			  directly from the mode argument of ioctl().
28351  *
28352  * Return Code: the code returned by sd_send_scsi_cmd()
28353  *		EFAULT if ddi_copyxxx() fails
28354  *		ENXIO if fail ddi_get_soft_state
28355  *		EINVAL if data pointer is NULL
28356  *		EIO if fail to reset block size
28357  *		EAGAIN if commands are in progress in the driver
28358  */
28359 
28360 static int
28361 sr_read_mode2(dev_t dev, caddr_t data, int flag)
28362 {
28363 	struct sd_lun		*un;
28364 	struct cdrom_read	mode2_struct;
28365 	struct cdrom_read	*mode2 = &mode2_struct;
28366 	int			rval;
28367 	uint32_t		restore_blksize;
28368 	struct uscsi_cmd	*com;
28369 	uchar_t			cdb[CDB_GROUP0];
28370 	int			nblocks;
28371 
28372 #ifdef _MULTI_DATAMODEL
28373 	/* To support ILP32 applications in an LP64 world */
28374 	struct cdrom_read32	cdrom_read32;
28375 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28376 #endif /* _MULTI_DATAMODEL */
28377 
28378 	if (data == NULL) {
28379 		return (EINVAL);
28380 	}
28381 
28382 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28383 	    (un->un_state == SD_STATE_OFFLINE)) {
28384 		return (ENXIO);
28385 	}
28386 
28387 	/*
28388 	 * Because this routine will update the device and driver block size
28389 	 * being used we want to make sure there are no commands in progress.
28390 	 * If commands are in progress the user will have to try again.
28391 	 *
28392 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
28393 	 * in sdioctl to protect commands from sdioctl through to the top of
28394 	 * sd_uscsi_strategy. See sdioctl for details.
28395 	 */
28396 	mutex_enter(SD_MUTEX(un));
28397 	if (un->un_ncmds_in_driver != 1) {
28398 		mutex_exit(SD_MUTEX(un));
28399 		return (EAGAIN);
28400 	}
28401 	mutex_exit(SD_MUTEX(un));
28402 
28403 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28404 	    "sd_read_mode2: entry: un:0x%p\n", un);
28405 
28406 #ifdef _MULTI_DATAMODEL
28407 	switch (ddi_model_convert_from(flag & FMODELS)) {
28408 	case DDI_MODEL_ILP32:
28409 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28410 			return (EFAULT);
28411 		}
28412 		/* Convert the ILP32 uscsi data from the application to LP64 */
28413 		cdrom_read32tocdrom_read(cdrd32, mode2);
28414 		break;
28415 	case DDI_MODEL_NONE:
28416 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28417 			return (EFAULT);
28418 		}
28419 		break;
28420 	}
28421 #else /* ! _MULTI_DATAMODEL */
28422 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
28423 		return (EFAULT);
28424 	}
28425 #endif /* _MULTI_DATAMODEL */
28426 
28427 	/* Store the current target block size for restoration later */
28428 	restore_blksize = un->un_tgt_blocksize;
28429 
28430 	/* Change the device and soft state target block size to 2336 */
28431 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
28432 		rval = EIO;
28433 		goto done;
28434 	}
28435 
28436 
28437 	bzero(cdb, sizeof (cdb));
28438 
28439 	/* set READ operation */
28440 	cdb[0] = SCMD_READ;
28441 
28442 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28443 	mode2->cdread_lba >>= 2;
28444 
28445 	/* set the start address */
28446 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28447 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28448 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28449 
28450 	/* set the transfer length */
28451 	nblocks = mode2->cdread_buflen / 2336;
28452 	cdb[4] = (uchar_t)nblocks & 0xFF;
28453 
28454 	/* build command */
28455 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28456 	com->uscsi_cdb = (caddr_t)cdb;
28457 	com->uscsi_cdblen = sizeof (cdb);
28458 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28459 	com->uscsi_buflen = mode2->cdread_buflen;
28460 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28461 
28462 	/*
28463 	 * Issue SCSI command with user space address for read buffer.
28464 	 *
28465 	 * This sends the command through main channel in the driver.
28466 	 *
28467 	 * Since this is accessed via an IOCTL call, we go through the
28468 	 * standard path, so that if the device was powered down, then
28469 	 * it would be 'awakened' to handle the command.
28470 	 */
28471 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_USERSPACE,
28472 	    UIO_SYSSPACE, SD_PATH_STANDARD);
28473 
28474 	kmem_free(com, sizeof (*com));
28475 
28476 	/* Restore the device and soft state target block size */
28477 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28478 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28479 		    "can't do switch back to mode 1\n");
28480 		/*
28481 		 * If sd_send_scsi_READ succeeded we still need to report
28482 		 * an error because we failed to reset the block size
28483 		 */
28484 		if (rval == 0) {
28485 			rval = EIO;
28486 		}
28487 	}
28488 
28489 done:
28490 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28491 	    "sd_read_mode2: exit: un:0x%p\n", un);
28492 
28493 	return (rval);
28494 }
28495 
28496 
28497 /*
28498  *    Function: sr_sector_mode()
28499  *
28500  * Description: This utility function is used by sr_read_mode2 to set the target
28501  *		block size based on the user specified size. This is a legacy
28502  *		implementation based upon a vendor specific mode page
28503  *
28504  *   Arguments: dev	- the device 'dev_t'
28505  *		data	- flag indicating if block size is being set to 2336 or
28506  *			  512.
28507  *
28508  * Return Code: the code returned by sd_send_scsi_cmd()
28509  *		EFAULT if ddi_copyxxx() fails
28510  *		ENXIO if fail ddi_get_soft_state
28511  *		EINVAL if data pointer is NULL
28512  */
28513 
28514 static int
28515 sr_sector_mode(dev_t dev, uint32_t blksize)
28516 {
28517 	struct sd_lun	*un;
28518 	uchar_t		*sense;
28519 	uchar_t		*select;
28520 	int		rval;
28521 
28522 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28523 	    (un->un_state == SD_STATE_OFFLINE)) {
28524 		return (ENXIO);
28525 	}
28526 
28527 	sense = kmem_zalloc(20, KM_SLEEP);
28528 
28529 	/* Note: This is a vendor specific mode page (0x81) */
28530 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
28531 	    SD_PATH_STANDARD)) != 0) {
28532 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28533 		    "sr_sector_mode: Mode Sense failed\n");
28534 		kmem_free(sense, 20);
28535 		return (rval);
28536 	}
28537 	select = kmem_zalloc(20, KM_SLEEP);
28538 	select[3] = 0x08;
28539 	select[10] = ((blksize >> 8) & 0xff);
28540 	select[11] = (blksize & 0xff);
28541 	select[12] = 0x01;
28542 	select[13] = 0x06;
28543 	select[14] = sense[14];
28544 	select[15] = sense[15];
28545 	if (blksize == SD_MODE2_BLKSIZE) {
28546 		select[14] |= 0x01;
28547 	}
28548 
28549 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
28550 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
28551 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28552 		    "sr_sector_mode: Mode Select failed\n");
28553 	} else {
28554 		/*
28555 		 * Only update the softstate block size if we successfully
28556 		 * changed the device block mode.
28557 		 */
28558 		mutex_enter(SD_MUTEX(un));
28559 		sd_update_block_info(un, blksize, 0);
28560 		mutex_exit(SD_MUTEX(un));
28561 	}
28562 	kmem_free(sense, 20);
28563 	kmem_free(select, 20);
28564 	return (rval);
28565 }
28566 
28567 
28568 /*
28569  *    Function: sr_read_cdda()
28570  *
28571  * Description: This routine is the driver entry point for handling CD-ROM
28572  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28573  *		the target supports CDDA these requests are handled via a vendor
28574  *		specific command (0xD8) If the target does not support CDDA
28575  *		these requests are handled via the READ CD command (0xBE).
28576  *
28577  *   Arguments: dev	- the device 'dev_t'
28578  *		data	- pointer to user provided CD-DA structure specifying
28579  *			  the track starting address, transfer length, and
28580  *			  subcode options.
28581  *		flag	- this argument is a pass through to ddi_copyxxx()
28582  *			  directly from the mode argument of ioctl().
28583  *
28584  * Return Code: the code returned by sd_send_scsi_cmd()
28585  *		EFAULT if ddi_copyxxx() fails
28586  *		ENXIO if fail ddi_get_soft_state
28587  *		EINVAL if invalid arguments are provided
28588  *		ENOTTY
28589  */
28590 
28591 static int
28592 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28593 {
28594 	struct sd_lun			*un;
28595 	struct uscsi_cmd		*com;
28596 	struct cdrom_cdda		*cdda;
28597 	int				rval;
28598 	size_t				buflen;
28599 	char				cdb[CDB_GROUP5];
28600 
28601 #ifdef _MULTI_DATAMODEL
28602 	/* To support ILP32 applications in an LP64 world */
28603 	struct cdrom_cdda32	cdrom_cdda32;
28604 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28605 #endif /* _MULTI_DATAMODEL */
28606 
28607 	if (data == NULL) {
28608 		return (EINVAL);
28609 	}
28610 
28611 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28612 		return (ENXIO);
28613 	}
28614 
28615 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28616 
28617 #ifdef _MULTI_DATAMODEL
28618 	switch (ddi_model_convert_from(flag & FMODELS)) {
28619 	case DDI_MODEL_ILP32:
28620 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28621 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28622 			    "sr_read_cdda: ddi_copyin Failed\n");
28623 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28624 			return (EFAULT);
28625 		}
28626 		/* Convert the ILP32 uscsi data from the application to LP64 */
28627 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28628 		break;
28629 	case DDI_MODEL_NONE:
28630 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28631 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28632 			    "sr_read_cdda: ddi_copyin Failed\n");
28633 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28634 			return (EFAULT);
28635 		}
28636 		break;
28637 	}
28638 #else /* ! _MULTI_DATAMODEL */
28639 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28640 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28641 		    "sr_read_cdda: ddi_copyin Failed\n");
28642 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28643 		return (EFAULT);
28644 	}
28645 #endif /* _MULTI_DATAMODEL */
28646 
28647 	/*
28648 	 * Since MMC-2 expects max 3 bytes for length, check if the
28649 	 * length input is greater than 3 bytes
28650 	 */
28651 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28652 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28653 		    "cdrom transfer length too large: %d (limit %d)\n",
28654 		    cdda->cdda_length, 0xFFFFFF);
28655 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28656 		return (EINVAL);
28657 	}
28658 
28659 	switch (cdda->cdda_subcode) {
28660 	case CDROM_DA_NO_SUBCODE:
28661 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28662 		break;
28663 	case CDROM_DA_SUBQ:
28664 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28665 		break;
28666 	case CDROM_DA_ALL_SUBCODE:
28667 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28668 		break;
28669 	case CDROM_DA_SUBCODE_ONLY:
28670 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28671 		break;
28672 	default:
28673 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28674 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28675 		    cdda->cdda_subcode);
28676 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28677 		return (EINVAL);
28678 	}
28679 
28680 	/* Build and send the command */
28681 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28682 	bzero(cdb, CDB_GROUP5);
28683 
28684 	if (un->un_f_cfg_cdda == TRUE) {
28685 		cdb[0] = (char)SCMD_READ_CD;
28686 		cdb[1] = 0x04;
28687 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28688 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28689 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28690 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28691 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28692 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28693 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28694 		cdb[9] = 0x10;
28695 		switch (cdda->cdda_subcode) {
28696 		case CDROM_DA_NO_SUBCODE :
28697 			cdb[10] = 0x0;
28698 			break;
28699 		case CDROM_DA_SUBQ :
28700 			cdb[10] = 0x2;
28701 			break;
28702 		case CDROM_DA_ALL_SUBCODE :
28703 			cdb[10] = 0x1;
28704 			break;
28705 		case CDROM_DA_SUBCODE_ONLY :
28706 			/* FALLTHROUGH */
28707 		default :
28708 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28709 			kmem_free(com, sizeof (*com));
28710 			return (ENOTTY);
28711 		}
28712 	} else {
28713 		cdb[0] = (char)SCMD_READ_CDDA;
28714 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28715 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28716 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28717 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28718 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28719 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28720 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28721 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28722 		cdb[10] = cdda->cdda_subcode;
28723 	}
28724 
28725 	com->uscsi_cdb = cdb;
28726 	com->uscsi_cdblen = CDB_GROUP5;
28727 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28728 	com->uscsi_buflen = buflen;
28729 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28730 
28731 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_USERSPACE,
28732 	    UIO_SYSSPACE, SD_PATH_STANDARD);
28733 
28734 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28735 	kmem_free(com, sizeof (*com));
28736 	return (rval);
28737 }
28738 
28739 
28740 /*
28741  *    Function: sr_read_cdxa()
28742  *
28743  * Description: This routine is the driver entry point for handling CD-ROM
28744  *		ioctl requests to return CD-XA (Extended Architecture) data.
28745  *		(CDROMCDXA).
28746  *
28747  *   Arguments: dev	- the device 'dev_t'
28748  *		data	- pointer to user provided CD-XA structure specifying
28749  *			  the data starting address, transfer length, and format
28750  *		flag	- this argument is a pass through to ddi_copyxxx()
28751  *			  directly from the mode argument of ioctl().
28752  *
28753  * Return Code: the code returned by sd_send_scsi_cmd()
28754  *		EFAULT if ddi_copyxxx() fails
28755  *		ENXIO if fail ddi_get_soft_state
28756  *		EINVAL if data pointer is NULL
28757  */
28758 
28759 static int
28760 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
28761 {
28762 	struct sd_lun		*un;
28763 	struct uscsi_cmd	*com;
28764 	struct cdrom_cdxa	*cdxa;
28765 	int			rval;
28766 	size_t			buflen;
28767 	char			cdb[CDB_GROUP5];
28768 	uchar_t			read_flags;
28769 
28770 #ifdef _MULTI_DATAMODEL
28771 	/* To support ILP32 applications in an LP64 world */
28772 	struct cdrom_cdxa32		cdrom_cdxa32;
28773 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
28774 #endif /* _MULTI_DATAMODEL */
28775 
28776 	if (data == NULL) {
28777 		return (EINVAL);
28778 	}
28779 
28780 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28781 		return (ENXIO);
28782 	}
28783 
28784 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
28785 
28786 #ifdef _MULTI_DATAMODEL
28787 	switch (ddi_model_convert_from(flag & FMODELS)) {
28788 	case DDI_MODEL_ILP32:
28789 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
28790 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28791 			return (EFAULT);
28792 		}
28793 		/*
28794 		 * Convert the ILP32 uscsi data from the
28795 		 * application to LP64 for internal use.
28796 		 */
28797 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
28798 		break;
28799 	case DDI_MODEL_NONE:
28800 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28801 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28802 			return (EFAULT);
28803 		}
28804 		break;
28805 	}
28806 #else /* ! _MULTI_DATAMODEL */
28807 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28808 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28809 		return (EFAULT);
28810 	}
28811 #endif /* _MULTI_DATAMODEL */
28812 
28813 	/*
28814 	 * Since MMC-2 expects max 3 bytes for length, check if the
28815 	 * length input is greater than 3 bytes
28816 	 */
28817 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
28818 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
28819 		    "cdrom transfer length too large: %d (limit %d)\n",
28820 		    cdxa->cdxa_length, 0xFFFFFF);
28821 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28822 		return (EINVAL);
28823 	}
28824 
28825 	switch (cdxa->cdxa_format) {
28826 	case CDROM_XA_DATA:
28827 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
28828 		read_flags = 0x10;
28829 		break;
28830 	case CDROM_XA_SECTOR_DATA:
28831 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
28832 		read_flags = 0xf8;
28833 		break;
28834 	case CDROM_XA_DATA_W_ERROR:
28835 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
28836 		read_flags = 0xfc;
28837 		break;
28838 	default:
28839 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28840 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
28841 		    cdxa->cdxa_format);
28842 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28843 		return (EINVAL);
28844 	}
28845 
28846 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28847 	bzero(cdb, CDB_GROUP5);
28848 	if (un->un_f_mmc_cap == TRUE) {
28849 		cdb[0] = (char)SCMD_READ_CD;
28850 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28851 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28852 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28853 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28854 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28855 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28856 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
28857 		cdb[9] = (char)read_flags;
28858 	} else {
28859 		/*
28860 		 * Note: A vendor specific command (0xDB) is being used her to
28861 		 * request a read of all subcodes.
28862 		 */
28863 		cdb[0] = (char)SCMD_READ_CDXA;
28864 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28865 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28866 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28867 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28868 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
28869 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28870 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28871 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
28872 		cdb[10] = cdxa->cdxa_format;
28873 	}
28874 	com->uscsi_cdb	   = cdb;
28875 	com->uscsi_cdblen  = CDB_GROUP5;
28876 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
28877 	com->uscsi_buflen  = buflen;
28878 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28879 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_USERSPACE,
28880 	    UIO_SYSSPACE, SD_PATH_STANDARD);
28881 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28882 	kmem_free(com, sizeof (*com));
28883 	return (rval);
28884 }
28885 
28886 
28887 /*
28888  *    Function: sr_eject()
28889  *
28890  * Description: This routine is the driver entry point for handling CD-ROM
28891  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
28892  *
28893  *   Arguments: dev	- the device 'dev_t'
28894  *
28895  * Return Code: the code returned by sd_send_scsi_cmd()
28896  */
28897 
28898 static int
28899 sr_eject(dev_t dev)
28900 {
28901 	struct sd_lun	*un;
28902 	int		rval;
28903 
28904 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28905 	    (un->un_state == SD_STATE_OFFLINE)) {
28906 		return (ENXIO);
28907 	}
28908 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
28909 	    SD_PATH_STANDARD)) != 0) {
28910 		return (rval);
28911 	}
28912 
28913 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
28914 	    SD_PATH_STANDARD);
28915 
28916 	if (rval == 0) {
28917 		mutex_enter(SD_MUTEX(un));
28918 		sr_ejected(un);
28919 		un->un_mediastate = DKIO_EJECTED;
28920 		cv_broadcast(&un->un_state_cv);
28921 		mutex_exit(SD_MUTEX(un));
28922 	}
28923 	return (rval);
28924 }
28925 
28926 
28927 /*
28928  *    Function: sr_ejected()
28929  *
28930  * Description: This routine updates the soft state structure to invalidate the
28931  *		geometry information after the media has been ejected or a
28932  *		media eject has been detected.
28933  *
28934  *   Arguments: un - driver soft state (unit) structure
28935  */
28936 
28937 static void
28938 sr_ejected(struct sd_lun *un)
28939 {
28940 	struct sd_errstats *stp;
28941 
28942 	ASSERT(un != NULL);
28943 	ASSERT(mutex_owned(SD_MUTEX(un)));
28944 
28945 	un->un_f_blockcount_is_valid	= FALSE;
28946 	un->un_f_tgt_blocksize_is_valid	= FALSE;
28947 	un->un_f_geometry_is_valid	= FALSE;
28948 
28949 	if (un->un_errstats != NULL) {
28950 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
28951 		stp->sd_capacity.value.ui64 = 0;
28952 	}
28953 }
28954 
28955 
28956 /*
28957  *    Function: sr_check_wp()
28958  *
28959  * Description: This routine checks the write protection of a removable media
28960  *		disk via the write protect bit of the Mode Page Header device
28961  *		specific field.  This routine has been implemented to use the
28962  *		error recovery mode page for all device types.
28963  *		Note: In the future use a sd_send_scsi_MODE_SENSE() routine
28964  *
28965  *   Arguments: dev		- the device 'dev_t'
28966  *
28967  * Return Code: int indicating if the device is write protected (1) or not (0)
28968  *
28969  *     Context: Kernel thread.
28970  *
28971  */
28972 
28973 static int
28974 sr_check_wp(dev_t dev)
28975 {
28976 	struct sd_lun	*un;
28977 	uchar_t		device_specific;
28978 	uchar_t		*sense;
28979 	int		hdrlen;
28980 	int		rval;
28981 	int		retry_flag = FALSE;
28982 
28983 	/*
28984 	 * Note: The return codes for this routine should be reworked to
28985 	 * properly handle the case of a NULL softstate.
28986 	 */
28987 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28988 		return (FALSE);
28989 	}
28990 
28991 	if (un->un_f_cfg_is_atapi == TRUE) {
28992 		retry_flag = TRUE;
28993 	}
28994 
28995 retry:
28996 	if (un->un_f_cfg_is_atapi == TRUE) {
28997 		/*
28998 		 * The mode page contents are not required; set the allocation
28999 		 * length for the mode page header only
29000 		 */
29001 		hdrlen = MODE_HEADER_LENGTH_GRP2;
29002 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29003 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
29004 		    MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
29005 		device_specific =
29006 		    ((struct mode_header_grp2 *)sense)->device_specific;
29007 	} else {
29008 		hdrlen = MODE_HEADER_LENGTH;
29009 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29010 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
29011 		    MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
29012 		device_specific =
29013 		    ((struct mode_header *)sense)->device_specific;
29014 	}
29015 
29016 	if (rval != 0) {
29017 		if ((un->un_f_cfg_is_atapi == TRUE) && (retry_flag)) {
29018 			/*
29019 			 * For an Atapi Zip drive, observed the drive
29020 			 * reporting check condition for the first attempt.
29021 			 * Sense data indicating power on or bus device/reset.
29022 			 * Hence in case of failure need to try at least once
29023 			 * for Atapi devices.
29024 			 */
29025 			retry_flag = FALSE;
29026 			kmem_free(sense, hdrlen);
29027 			goto retry;
29028 		} else {
29029 			/*
29030 			 * Write protect mode sense failed; not all disks
29031 			 * understand this query. Return FALSE assuming that
29032 			 * these devices are not writable.
29033 			 */
29034 			rval = FALSE;
29035 		}
29036 	} else {
29037 		if (device_specific & WRITE_PROTECT) {
29038 			rval = TRUE;
29039 		} else {
29040 			rval = FALSE;
29041 		}
29042 	}
29043 	kmem_free(sense, hdrlen);
29044 	return (rval);
29045 }
29046 
29047 
29048 /*
29049  *    Function: sr_volume_ctrl()
29050  *
29051  * Description: This routine is the driver entry point for handling CD-ROM
29052  *		audio output volume ioctl requests. (CDROMVOLCTRL)
29053  *
29054  *   Arguments: dev	- the device 'dev_t'
29055  *		data	- pointer to user audio volume control structure
29056  *		flag	- this argument is a pass through to ddi_copyxxx()
29057  *			  directly from the mode argument of ioctl().
29058  *
29059  * Return Code: the code returned by sd_send_scsi_cmd()
29060  *		EFAULT if ddi_copyxxx() fails
29061  *		ENXIO if fail ddi_get_soft_state
29062  *		EINVAL if data pointer is NULL
29063  *
29064  */
29065 
29066 static int
29067 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
29068 {
29069 	struct sd_lun		*un;
29070 	struct cdrom_volctrl    volume;
29071 	struct cdrom_volctrl    *vol = &volume;
29072 	uchar_t			*sense_page;
29073 	uchar_t			*select_page;
29074 	uchar_t			*sense;
29075 	uchar_t			*select;
29076 	int			sense_buflen;
29077 	int			select_buflen;
29078 	int			rval;
29079 
29080 	if (data == NULL) {
29081 		return (EINVAL);
29082 	}
29083 
29084 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29085 	    (un->un_state == SD_STATE_OFFLINE)) {
29086 		return (ENXIO);
29087 	}
29088 
29089 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
29090 		return (EFAULT);
29091 	}
29092 
29093 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29094 		struct mode_header_grp2		*sense_mhp;
29095 		struct mode_header_grp2		*select_mhp;
29096 		int				bd_len;
29097 
29098 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
29099 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
29100 		    MODEPAGE_AUDIO_CTRL_LEN;
29101 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29102 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29103 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
29104 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29105 		    SD_PATH_STANDARD)) != 0) {
29106 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
29107 			    "sr_volume_ctrl: Mode Sense Failed\n");
29108 			kmem_free(sense, sense_buflen);
29109 			kmem_free(select, select_buflen);
29110 			return (rval);
29111 		}
29112 		sense_mhp = (struct mode_header_grp2 *)sense;
29113 		select_mhp = (struct mode_header_grp2 *)select;
29114 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
29115 		    sense_mhp->bdesc_length_lo;
29116 		if (bd_len > MODE_BLK_DESC_LENGTH) {
29117 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29118 			    "sr_volume_ctrl: Mode Sense returned invalid "
29119 			    "block descriptor length\n");
29120 			kmem_free(sense, sense_buflen);
29121 			kmem_free(select, select_buflen);
29122 			return (EIO);
29123 		}
29124 		sense_page = (uchar_t *)
29125 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
29126 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
29127 		select_mhp->length_msb = 0;
29128 		select_mhp->length_lsb = 0;
29129 		select_mhp->bdesc_length_hi = 0;
29130 		select_mhp->bdesc_length_lo = 0;
29131 	} else {
29132 		struct mode_header		*sense_mhp, *select_mhp;
29133 
29134 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29135 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29136 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29137 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29138 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
29139 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29140 		    SD_PATH_STANDARD)) != 0) {
29141 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29142 			    "sr_volume_ctrl: Mode Sense Failed\n");
29143 			kmem_free(sense, sense_buflen);
29144 			kmem_free(select, select_buflen);
29145 			return (rval);
29146 		}
29147 		sense_mhp  = (struct mode_header *)sense;
29148 		select_mhp = (struct mode_header *)select;
29149 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
29150 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29151 			    "sr_volume_ctrl: Mode Sense returned invalid "
29152 			    "block descriptor length\n");
29153 			kmem_free(sense, sense_buflen);
29154 			kmem_free(select, select_buflen);
29155 			return (EIO);
29156 		}
29157 		sense_page = (uchar_t *)
29158 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
29159 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
29160 		select_mhp->length = 0;
29161 		select_mhp->bdesc_length = 0;
29162 	}
29163 	/*
29164 	 * Note: An audio control data structure could be created and overlayed
29165 	 * on the following in place of the array indexing method implemented.
29166 	 */
29167 
29168 	/* Build the select data for the user volume data */
29169 	select_page[0] = MODEPAGE_AUDIO_CTRL;
29170 	select_page[1] = 0xE;
29171 	/* Set the immediate bit */
29172 	select_page[2] = 0x04;
29173 	/* Zero out reserved fields */
29174 	select_page[3] = 0x00;
29175 	select_page[4] = 0x00;
29176 	/* Return sense data for fields not to be modified */
29177 	select_page[5] = sense_page[5];
29178 	select_page[6] = sense_page[6];
29179 	select_page[7] = sense_page[7];
29180 	/* Set the user specified volume levels for channel 0 and 1 */
29181 	select_page[8] = 0x01;
29182 	select_page[9] = vol->channel0;
29183 	select_page[10] = 0x02;
29184 	select_page[11] = vol->channel1;
29185 	/* Channel 2 and 3 are currently unsupported so return the sense data */
29186 	select_page[12] = sense_page[12];
29187 	select_page[13] = sense_page[13];
29188 	select_page[14] = sense_page[14];
29189 	select_page[15] = sense_page[15];
29190 
29191 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29192 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
29193 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29194 	} else {
29195 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
29196 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29197 	}
29198 
29199 	kmem_free(sense, sense_buflen);
29200 	kmem_free(select, select_buflen);
29201 	return (rval);
29202 }
29203 
29204 
29205 /*
29206  *    Function: sr_read_sony_session_offset()
29207  *
29208  * Description: This routine is the driver entry point for handling CD-ROM
29209  *		ioctl requests for session offset information. (CDROMREADOFFSET)
29210  *		The address of the first track in the last session of a
29211  *		multi-session CD-ROM is returned
29212  *
29213  *		Note: This routine uses a vendor specific key value in the
29214  *		command control field without implementing any vendor check here
29215  *		or in the ioctl routine.
29216  *
29217  *   Arguments: dev	- the device 'dev_t'
29218  *		data	- pointer to an int to hold the requested address
29219  *		flag	- this argument is a pass through to ddi_copyxxx()
29220  *			  directly from the mode argument of ioctl().
29221  *
29222  * Return Code: the code returned by sd_send_scsi_cmd()
29223  *		EFAULT if ddi_copyxxx() fails
29224  *		ENXIO if fail ddi_get_soft_state
29225  *		EINVAL if data pointer is NULL
29226  */
29227 
29228 static int
29229 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
29230 {
29231 	struct sd_lun		*un;
29232 	struct uscsi_cmd	*com;
29233 	caddr_t			buffer;
29234 	char			cdb[CDB_GROUP1];
29235 	int			session_offset = 0;
29236 	int			rval;
29237 
29238 	if (data == NULL) {
29239 		return (EINVAL);
29240 	}
29241 
29242 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29243 	    (un->un_state == SD_STATE_OFFLINE)) {
29244 		return (ENXIO);
29245 	}
29246 
29247 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
29248 	bzero(cdb, CDB_GROUP1);
29249 	cdb[0] = SCMD_READ_TOC;
29250 	/*
29251 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
29252 	 * (4 byte TOC response header + 8 byte response data)
29253 	 */
29254 	cdb[8] = SONY_SESSION_OFFSET_LEN;
29255 	/* Byte 9 is the control byte. A vendor specific value is used */
29256 	cdb[9] = SONY_SESSION_OFFSET_KEY;
29257 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29258 	com->uscsi_cdb = cdb;
29259 	com->uscsi_cdblen = CDB_GROUP1;
29260 	com->uscsi_bufaddr = buffer;
29261 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
29262 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
29263 
29264 	rval = sd_send_scsi_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
29265 	    UIO_SYSSPACE, SD_PATH_STANDARD);
29266 	if (rval != 0) {
29267 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29268 		kmem_free(com, sizeof (*com));
29269 		return (rval);
29270 	}
29271 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
29272 		session_offset =
29273 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
29274 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
29275 		/*
29276 		 * Offset returned offset in current lbasize block's. Convert to
29277 		 * 2k block's to return to the user
29278 		 */
29279 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
29280 			session_offset >>= 2;
29281 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
29282 			session_offset >>= 1;
29283 		}
29284 	}
29285 
29286 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
29287 		rval = EFAULT;
29288 	}
29289 
29290 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29291 	kmem_free(com, sizeof (*com));
29292 	return (rval);
29293 }
29294 
29295 
29296 /*
29297  *    Function: sd_wm_cache_constructor()
29298  *
29299  * Description: Cache Constructor for the wmap cache for the read/modify/write
29300  * 		devices.
29301  *
29302  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29303  *		un	- sd_lun structure for the device.
29304  *		flag	- the km flags passed to constructor
29305  *
29306  * Return Code: 0 on success.
29307  *		-1 on failure.
29308  */
29309 
29310 /*ARGSUSED*/
29311 static int
29312 sd_wm_cache_constructor(void *wm, void *un, int flags)
29313 {
29314 	bzero(wm, sizeof (struct sd_w_map));
29315 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
29316 	return (0);
29317 }
29318 
29319 
29320 /*
29321  *    Function: sd_wm_cache_destructor()
29322  *
29323  * Description: Cache destructor for the wmap cache for the read/modify/write
29324  * 		devices.
29325  *
29326  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29327  *		un	- sd_lun structure for the device.
29328  */
29329 /*ARGSUSED*/
29330 static void
29331 sd_wm_cache_destructor(void *wm, void *un)
29332 {
29333 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
29334 }
29335 
29336 
29337 /*
29338  *    Function: sd_range_lock()
29339  *
29340  * Description: Lock the range of blocks specified as parameter to ensure
29341  *		that read, modify write is atomic and no other i/o writes
29342  *		to the same location. The range is specified in terms
29343  *		of start and end blocks. Block numbers are the actual
29344  *		media block numbers and not system.
29345  *
29346  *   Arguments: un	- sd_lun structure for the device.
29347  *		startb - The starting block number
29348  *		endb - The end block number
29349  *		typ - type of i/o - simple/read_modify_write
29350  *
29351  * Return Code: wm  - pointer to the wmap structure.
29352  *
29353  *     Context: This routine can sleep.
29354  */
29355 
29356 static struct sd_w_map *
29357 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
29358 {
29359 	struct sd_w_map *wmp = NULL;
29360 	struct sd_w_map *sl_wmp = NULL;
29361 	struct sd_w_map *tmp_wmp;
29362 	wm_state state = SD_WM_CHK_LIST;
29363 
29364 
29365 	ASSERT(un != NULL);
29366 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29367 
29368 	mutex_enter(SD_MUTEX(un));
29369 
29370 	while (state != SD_WM_DONE) {
29371 
29372 		switch (state) {
29373 		case SD_WM_CHK_LIST:
29374 			/*
29375 			 * This is the starting state. Check the wmap list
29376 			 * to see if the range is currently available.
29377 			 */
29378 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
29379 				/*
29380 				 * If this is a simple write and no rmw
29381 				 * i/o is pending then try to lock the
29382 				 * range as the range should be available.
29383 				 */
29384 				state = SD_WM_LOCK_RANGE;
29385 			} else {
29386 				tmp_wmp = sd_get_range(un, startb, endb);
29387 				if (tmp_wmp != NULL) {
29388 					if ((wmp != NULL) && ONLIST(un, wmp)) {
29389 						/*
29390 						 * Should not keep onlist wmps
29391 						 * while waiting this macro
29392 						 * will also do wmp = NULL;
29393 						 */
29394 						FREE_ONLIST_WMAP(un, wmp);
29395 					}
29396 					/*
29397 					 * sl_wmp is the wmap on which wait
29398 					 * is done, since the tmp_wmp points
29399 					 * to the inuse wmap, set sl_wmp to
29400 					 * tmp_wmp and change the state to sleep
29401 					 */
29402 					sl_wmp = tmp_wmp;
29403 					state = SD_WM_WAIT_MAP;
29404 				} else {
29405 					state = SD_WM_LOCK_RANGE;
29406 				}
29407 
29408 			}
29409 			break;
29410 
29411 		case SD_WM_LOCK_RANGE:
29412 			ASSERT(un->un_wm_cache);
29413 			/*
29414 			 * The range need to be locked, try to get a wmap.
29415 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29416 			 * if possible as we will have to release the sd mutex
29417 			 * if we have to sleep.
29418 			 */
29419 			if (wmp == NULL)
29420 				wmp = kmem_cache_alloc(un->un_wm_cache,
29421 				    KM_NOSLEEP);
29422 			if (wmp == NULL) {
29423 				mutex_exit(SD_MUTEX(un));
29424 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29425 				    (sd_lun::un_wm_cache))
29426 				wmp = kmem_cache_alloc(un->un_wm_cache,
29427 				    KM_SLEEP);
29428 				mutex_enter(SD_MUTEX(un));
29429 				/*
29430 				 * we released the mutex so recheck and go to
29431 				 * check list state.
29432 				 */
29433 				state = SD_WM_CHK_LIST;
29434 			} else {
29435 				/*
29436 				 * We exit out of state machine since we
29437 				 * have the wmap. Do the housekeeping first.
29438 				 * place the wmap on the wmap list if it is not
29439 				 * on it already and then set the state to done.
29440 				 */
29441 				wmp->wm_start = startb;
29442 				wmp->wm_end = endb;
29443 				wmp->wm_flags = typ | SD_WM_BUSY;
29444 				if (typ & SD_WTYPE_RMW) {
29445 					un->un_rmw_count++;
29446 				}
29447 				/*
29448 				 * If not already on the list then link
29449 				 */
29450 				if (!ONLIST(un, wmp)) {
29451 					wmp->wm_next = un->un_wm;
29452 					wmp->wm_prev = NULL;
29453 					if (wmp->wm_next)
29454 						wmp->wm_next->wm_prev = wmp;
29455 					un->un_wm = wmp;
29456 				}
29457 				state = SD_WM_DONE;
29458 			}
29459 			break;
29460 
29461 		case SD_WM_WAIT_MAP:
29462 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29463 			/*
29464 			 * Wait is done on sl_wmp, which is set in the
29465 			 * check_list state.
29466 			 */
29467 			sl_wmp->wm_wanted_count++;
29468 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29469 			sl_wmp->wm_wanted_count--;
29470 			/*
29471 			 * We can reuse the memory from the completed sl_wmp
29472 			 * lock range for our new lock, but only if noone is
29473 			 * waiting for it.
29474 			 */
29475 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29476 			if (sl_wmp->wm_wanted_count == 0) {
29477 				if (wmp != NULL)
29478 					CHK_N_FREEWMP(un, wmp);
29479 				wmp = sl_wmp;
29480 			}
29481 			sl_wmp = NULL;
29482 			/*
29483 			 * After waking up, need to recheck for availability of
29484 			 * range.
29485 			 */
29486 			state = SD_WM_CHK_LIST;
29487 			break;
29488 
29489 		default:
29490 			panic("sd_range_lock: "
29491 			    "Unknown state %d in sd_range_lock", state);
29492 			/*NOTREACHED*/
29493 		} /* switch(state) */
29494 
29495 	} /* while(state != SD_WM_DONE) */
29496 
29497 	mutex_exit(SD_MUTEX(un));
29498 
29499 	ASSERT(wmp != NULL);
29500 
29501 	return (wmp);
29502 }
29503 
29504 
29505 /*
29506  *    Function: sd_get_range()
29507  *
29508  * Description: Find if there any overlapping I/O to this one
29509  *		Returns the write-map of 1st such I/O, NULL otherwise.
29510  *
29511  *   Arguments: un	- sd_lun structure for the device.
29512  *		startb - The starting block number
29513  *		endb - The end block number
29514  *
29515  * Return Code: wm  - pointer to the wmap structure.
29516  */
29517 
29518 static struct sd_w_map *
29519 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29520 {
29521 	struct sd_w_map *wmp;
29522 
29523 	ASSERT(un != NULL);
29524 
29525 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29526 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29527 			continue;
29528 		}
29529 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29530 			break;
29531 		}
29532 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29533 			break;
29534 		}
29535 	}
29536 
29537 	return (wmp);
29538 }
29539 
29540 
29541 /*
29542  *    Function: sd_free_inlist_wmap()
29543  *
29544  * Description: Unlink and free a write map struct.
29545  *
29546  *   Arguments: un      - sd_lun structure for the device.
29547  *		wmp	- sd_w_map which needs to be unlinked.
29548  */
29549 
29550 static void
29551 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29552 {
29553 	ASSERT(un != NULL);
29554 
29555 	if (un->un_wm == wmp) {
29556 		un->un_wm = wmp->wm_next;
29557 	} else {
29558 		wmp->wm_prev->wm_next = wmp->wm_next;
29559 	}
29560 
29561 	if (wmp->wm_next) {
29562 		wmp->wm_next->wm_prev = wmp->wm_prev;
29563 	}
29564 
29565 	wmp->wm_next = wmp->wm_prev = NULL;
29566 
29567 	kmem_cache_free(un->un_wm_cache, wmp);
29568 }
29569 
29570 
29571 /*
29572  *    Function: sd_range_unlock()
29573  *
29574  * Description: Unlock the range locked by wm.
29575  *		Free write map if nobody else is waiting on it.
29576  *
29577  *   Arguments: un      - sd_lun structure for the device.
29578  *              wmp     - sd_w_map which needs to be unlinked.
29579  */
29580 
29581 static void
29582 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29583 {
29584 	ASSERT(un != NULL);
29585 	ASSERT(wm != NULL);
29586 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29587 
29588 	mutex_enter(SD_MUTEX(un));
29589 
29590 	if (wm->wm_flags & SD_WTYPE_RMW) {
29591 		un->un_rmw_count--;
29592 	}
29593 
29594 	if (wm->wm_wanted_count) {
29595 		wm->wm_flags = 0;
29596 		/*
29597 		 * Broadcast that the wmap is available now.
29598 		 */
29599 		cv_broadcast(&wm->wm_avail);
29600 	} else {
29601 		/*
29602 		 * If no one is waiting on the map, it should be free'ed.
29603 		 */
29604 		sd_free_inlist_wmap(un, wm);
29605 	}
29606 
29607 	mutex_exit(SD_MUTEX(un));
29608 }
29609 
29610 
29611 /*
29612  *    Function: sd_read_modify_write_task
29613  *
29614  * Description: Called from a taskq thread to initiate the write phase of
29615  *		a read-modify-write request.  This is used for targets where
29616  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29617  *
29618  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29619  *
29620  *     Context: Called under taskq thread context.
29621  */
29622 
29623 static void
29624 sd_read_modify_write_task(void *arg)
29625 {
29626 	struct sd_mapblocksize_info	*bsp;
29627 	struct buf	*bp;
29628 	struct sd_xbuf	*xp;
29629 	struct sd_lun	*un;
29630 
29631 	bp = arg;	/* The bp is given in arg */
29632 	ASSERT(bp != NULL);
29633 
29634 	/* Get the pointer to the layer-private data struct */
29635 	xp = SD_GET_XBUF(bp);
29636 	ASSERT(xp != NULL);
29637 	bsp = xp->xb_private;
29638 	ASSERT(bsp != NULL);
29639 
29640 	un = SD_GET_UN(bp);
29641 	ASSERT(un != NULL);
29642 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29643 
29644 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29645 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29646 
29647 	/*
29648 	 * This is the write phase of a read-modify-write request, called
29649 	 * under the context of a taskq thread in response to the completion
29650 	 * of the read portion of the rmw request completing under interrupt
29651 	 * context. The write request must be sent from here down the iostart
29652 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29653 	 * we use the layer index saved in the layer-private data area.
29654 	 */
29655 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29656 
29657 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29658 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29659 }
29660 
29661 
29662 /*
29663  *    Function: sddump_do_read_of_rmw()
29664  *
29665  * Description: This routine will be called from sddump, If sddump is called
29666  *		with an I/O which not aligned on device blocksize boundary
29667  *		then the write has to be converted to read-modify-write.
29668  *		Do the read part here in order to keep sddump simple.
29669  *		Note - That the sd_mutex is held across the call to this
29670  *		routine.
29671  *
29672  *   Arguments: un	- sd_lun
29673  *		blkno	- block number in terms of media block size.
29674  *		nblk	- number of blocks.
29675  *		bpp	- pointer to pointer to the buf structure. On return
29676  *			from this function, *bpp points to the valid buffer
29677  *			to which the write has to be done.
29678  *
29679  * Return Code: 0 for success or errno-type return code
29680  */
29681 
29682 static int
29683 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29684 	struct buf **bpp)
29685 {
29686 	int err;
29687 	int i;
29688 	int rval;
29689 	struct buf *bp;
29690 	struct scsi_pkt *pkt = NULL;
29691 	uint32_t target_blocksize;
29692 
29693 	ASSERT(un != NULL);
29694 	ASSERT(mutex_owned(SD_MUTEX(un)));
29695 
29696 	target_blocksize = un->un_tgt_blocksize;
29697 
29698 	mutex_exit(SD_MUTEX(un));
29699 
29700 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29701 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29702 	if (bp == NULL) {
29703 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
29704 		    "no resources for dumping; giving up");
29705 		err = ENOMEM;
29706 		goto done;
29707 	}
29708 
29709 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
29710 	    blkno, nblk);
29711 	if (rval != 0) {
29712 		scsi_free_consistent_buf(bp);
29713 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
29714 		    "no resources for dumping; giving up");
29715 		err = ENOMEM;
29716 		goto done;
29717 	}
29718 
29719 	pkt->pkt_flags |= FLAG_NOINTR;
29720 
29721 	err = EIO;
29722 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
29723 
29724 		/*
29725 		 * Scsi_poll returns 0 (success) if the command completes and
29726 		 * the status block is STATUS_GOOD.  We should only check
29727 		 * errors if this condition is not true.  Even then we should
29728 		 * send our own request sense packet only if we have a check
29729 		 * condition and auto request sense has not been performed by
29730 		 * the hba.
29731 		 */
29732 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
29733 
29734 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
29735 			err = 0;
29736 			break;
29737 		}
29738 
29739 		/*
29740 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
29741 		 * no need to read RQS data.
29742 		 */
29743 		if (pkt->pkt_reason == CMD_DEV_GONE) {
29744 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
29745 			    "Device is gone\n");
29746 			break;
29747 		}
29748 
29749 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
29750 			SD_INFO(SD_LOG_DUMP, un,
29751 			    "sddump: read failed with CHECK, try # %d\n", i);
29752 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
29753 				(void) sd_send_polled_RQS(un);
29754 			}
29755 
29756 			continue;
29757 		}
29758 
29759 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
29760 			int reset_retval = 0;
29761 
29762 			SD_INFO(SD_LOG_DUMP, un,
29763 			    "sddump: read failed with BUSY, try # %d\n", i);
29764 
29765 			if (un->un_f_lun_reset_enabled == TRUE) {
29766 				reset_retval = scsi_reset(SD_ADDRESS(un),
29767 				    RESET_LUN);
29768 			}
29769 			if (reset_retval == 0) {
29770 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
29771 			}
29772 			(void) sd_send_polled_RQS(un);
29773 
29774 		} else {
29775 			SD_INFO(SD_LOG_DUMP, un,
29776 			    "sddump: read failed with 0x%x, try # %d\n",
29777 			    SD_GET_PKT_STATUS(pkt), i);
29778 			mutex_enter(SD_MUTEX(un));
29779 			sd_reset_target(un, pkt);
29780 			mutex_exit(SD_MUTEX(un));
29781 		}
29782 
29783 		/*
29784 		 * If we are not getting anywhere with lun/target resets,
29785 		 * let's reset the bus.
29786 		 */
29787 		if (i > SD_NDUMP_RETRIES/2) {
29788 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
29789 			(void) sd_send_polled_RQS(un);
29790 		}
29791 
29792 	}
29793 	scsi_destroy_pkt(pkt);
29794 
29795 	if (err != 0) {
29796 		scsi_free_consistent_buf(bp);
29797 		*bpp = NULL;
29798 	} else {
29799 		*bpp = bp;
29800 	}
29801 
29802 done:
29803 	mutex_enter(SD_MUTEX(un));
29804 	return (err);
29805 }
29806 
29807 
29808 /*
29809  *    Function: sd_failfast_flushq
29810  *
29811  * Description: Take all bp's on the wait queue that have B_FAILFAST set
29812  *		in b_flags and move them onto the failfast queue, then kick
29813  *		off a thread to return all bp's on the failfast queue to
29814  *		their owners with an error set.
29815  *
29816  *   Arguments: un - pointer to the soft state struct for the instance.
29817  *
29818  *     Context: may execute in interrupt context.
29819  */
29820 
29821 static void
29822 sd_failfast_flushq(struct sd_lun *un)
29823 {
29824 	struct buf *bp;
29825 	struct buf *next_waitq_bp;
29826 	struct buf *prev_waitq_bp = NULL;
29827 
29828 	ASSERT(un != NULL);
29829 	ASSERT(mutex_owned(SD_MUTEX(un)));
29830 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
29831 	ASSERT(un->un_failfast_bp == NULL);
29832 
29833 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29834 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
29835 
29836 	/*
29837 	 * Check if we should flush all bufs when entering failfast state, or
29838 	 * just those with B_FAILFAST set.
29839 	 */
29840 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
29841 		/*
29842 		 * Move *all* bp's on the wait queue to the failfast flush
29843 		 * queue, including those that do NOT have B_FAILFAST set.
29844 		 */
29845 		if (un->un_failfast_headp == NULL) {
29846 			ASSERT(un->un_failfast_tailp == NULL);
29847 			un->un_failfast_headp = un->un_waitq_headp;
29848 		} else {
29849 			ASSERT(un->un_failfast_tailp != NULL);
29850 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
29851 		}
29852 
29853 		un->un_failfast_tailp = un->un_waitq_tailp;
29854 
29855 		/* update kstat for each bp moved out of the waitq */
29856 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
29857 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29858 		}
29859 
29860 		/* empty the waitq */
29861 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
29862 
29863 	} else {
29864 		/*
29865 		 * Go thru the wait queue, pick off all entries with
29866 		 * B_FAILFAST set, and move these onto the failfast queue.
29867 		 */
29868 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
29869 			/*
29870 			 * Save the pointer to the next bp on the wait queue,
29871 			 * so we get to it on the next iteration of this loop.
29872 			 */
29873 			next_waitq_bp = bp->av_forw;
29874 
29875 			/*
29876 			 * If this bp from the wait queue does NOT have
29877 			 * B_FAILFAST set, just move on to the next element
29878 			 * in the wait queue. Note, this is the only place
29879 			 * where it is correct to set prev_waitq_bp.
29880 			 */
29881 			if ((bp->b_flags & B_FAILFAST) == 0) {
29882 				prev_waitq_bp = bp;
29883 				continue;
29884 			}
29885 
29886 			/*
29887 			 * Remove the bp from the wait queue.
29888 			 */
29889 			if (bp == un->un_waitq_headp) {
29890 				/* The bp is the first element of the waitq. */
29891 				un->un_waitq_headp = next_waitq_bp;
29892 				if (un->un_waitq_headp == NULL) {
29893 					/* The wait queue is now empty */
29894 					un->un_waitq_tailp = NULL;
29895 				}
29896 			} else {
29897 				/*
29898 				 * The bp is either somewhere in the middle
29899 				 * or at the end of the wait queue.
29900 				 */
29901 				ASSERT(un->un_waitq_headp != NULL);
29902 				ASSERT(prev_waitq_bp != NULL);
29903 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
29904 				    == 0);
29905 				if (bp == un->un_waitq_tailp) {
29906 					/* bp is the last entry on the waitq. */
29907 					ASSERT(next_waitq_bp == NULL);
29908 					un->un_waitq_tailp = prev_waitq_bp;
29909 				}
29910 				prev_waitq_bp->av_forw = next_waitq_bp;
29911 			}
29912 			bp->av_forw = NULL;
29913 
29914 			/*
29915 			 * update kstat since the bp is moved out of
29916 			 * the waitq
29917 			 */
29918 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29919 
29920 			/*
29921 			 * Now put the bp onto the failfast queue.
29922 			 */
29923 			if (un->un_failfast_headp == NULL) {
29924 				/* failfast queue is currently empty */
29925 				ASSERT(un->un_failfast_tailp == NULL);
29926 				un->un_failfast_headp =
29927 				    un->un_failfast_tailp = bp;
29928 			} else {
29929 				/* Add the bp to the end of the failfast q */
29930 				ASSERT(un->un_failfast_tailp != NULL);
29931 				ASSERT(un->un_failfast_tailp->b_flags &
29932 				    B_FAILFAST);
29933 				un->un_failfast_tailp->av_forw = bp;
29934 				un->un_failfast_tailp = bp;
29935 			}
29936 		}
29937 	}
29938 
29939 	/*
29940 	 * Now return all bp's on the failfast queue to their owners.
29941 	 */
29942 	while ((bp = un->un_failfast_headp) != NULL) {
29943 
29944 		un->un_failfast_headp = bp->av_forw;
29945 		if (un->un_failfast_headp == NULL) {
29946 			un->un_failfast_tailp = NULL;
29947 		}
29948 
29949 		/*
29950 		 * We want to return the bp with a failure error code, but
29951 		 * we do not want a call to sd_start_cmds() to occur here,
29952 		 * so use sd_return_failed_command_no_restart() instead of
29953 		 * sd_return_failed_command().
29954 		 */
29955 		sd_return_failed_command_no_restart(un, bp, EIO);
29956 	}
29957 
29958 	/* Flush the xbuf queues if required. */
29959 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
29960 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
29961 	}
29962 
29963 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29964 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
29965 }
29966 
29967 
29968 /*
29969  *    Function: sd_failfast_flushq_callback
29970  *
29971  * Description: Return TRUE if the given bp meets the criteria for failfast
29972  *		flushing. Used with ddi_xbuf_flushq(9F).
29973  *
29974  *   Arguments: bp - ptr to buf struct to be examined.
29975  *
29976  *     Context: Any
29977  */
29978 
29979 static int
29980 sd_failfast_flushq_callback(struct buf *bp)
29981 {
29982 	/*
29983 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
29984 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
29985 	 */
29986 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
29987 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
29988 }
29989 
29990 
29991 
29992 #if defined(__i386) || defined(__amd64)
29993 /*
29994  * Function: sd_setup_next_xfer
29995  *
29996  * Description: Prepare next I/O operation using DMA_PARTIAL
29997  *
29998  */
29999 
30000 static int
30001 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
30002     struct scsi_pkt *pkt, struct sd_xbuf *xp)
30003 {
30004 	ssize_t	num_blks_not_xfered;
30005 	daddr_t	strt_blk_num;
30006 	ssize_t	bytes_not_xfered;
30007 	int	rval;
30008 
30009 	ASSERT(pkt->pkt_resid == 0);
30010 
30011 	/*
30012 	 * Calculate next block number and amount to be transferred.
30013 	 *
30014 	 * How much data NOT transfered to the HBA yet.
30015 	 */
30016 	bytes_not_xfered = xp->xb_dma_resid;
30017 
30018 	/*
30019 	 * figure how many blocks NOT transfered to the HBA yet.
30020 	 */
30021 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
30022 
30023 	/*
30024 	 * set starting block number to the end of what WAS transfered.
30025 	 */
30026 	strt_blk_num = xp->xb_blkno +
30027 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
30028 
30029 	/*
30030 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
30031 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
30032 	 * the disk mutex here.
30033 	 */
30034 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
30035 	    strt_blk_num, num_blks_not_xfered);
30036 
30037 	if (rval == 0) {
30038 
30039 		/*
30040 		 * Success.
30041 		 *
30042 		 * Adjust things if there are still more blocks to be
30043 		 * transfered.
30044 		 */
30045 		xp->xb_dma_resid = pkt->pkt_resid;
30046 		pkt->pkt_resid = 0;
30047 
30048 		return (1);
30049 	}
30050 
30051 	/*
30052 	 * There's really only one possible return value from
30053 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
30054 	 * returns NULL.
30055 	 */
30056 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
30057 
30058 	bp->b_resid = bp->b_bcount;
30059 	bp->b_flags |= B_ERROR;
30060 
30061 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30062 	    "Error setting up next portion of DMA transfer\n");
30063 
30064 	return (0);
30065 }
30066 #endif
30067 
30068 /*
30069  *    Function: sd_panic_for_res_conflict
30070  *
30071  * Description: Call panic with a string formated with "Reservation Conflict"
30072  *		and a human readable identifier indicating the SD instance
30073  *		that experienced the reservation conflict.
30074  *
30075  *   Arguments: un - pointer to the soft state struct for the instance.
30076  *
30077  *     Context: may execute in interrupt context.
30078  */
30079 
30080 #define	SD_RESV_CONFLICT_FMT_LEN 40
30081 void
30082 sd_panic_for_res_conflict(struct sd_lun *un)
30083 {
30084 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
30085 	char path_str[MAXPATHLEN];
30086 
30087 	(void) snprintf(panic_str, sizeof (panic_str),
30088 	    "Reservation Conflict\nDisk: %s",
30089 	    ddi_pathname(SD_DEVINFO(un), path_str));
30090 
30091 	panic(panic_str);
30092 }
30093 
30094 /*
30095  * Note: The following sd_faultinjection_ioctl( ) routines implement
30096  * driver support for handling fault injection for error analysis
30097  * causing faults in multiple layers of the driver.
30098  *
30099  */
30100 
30101 #ifdef SD_FAULT_INJECTION
30102 static uint_t   sd_fault_injection_on = 0;
30103 
30104 /*
30105  *    Function: sd_faultinjection_ioctl()
30106  *
30107  * Description: This routine is the driver entry point for handling
30108  *              faultinjection ioctls to inject errors into the
30109  *              layer model
30110  *
30111  *   Arguments: cmd	- the ioctl cmd recieved
30112  *		arg	- the arguments from user and returns
30113  */
30114 
30115 static void
30116 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
30117 
30118 	uint_t i;
30119 	uint_t rval;
30120 
30121 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
30122 
30123 	mutex_enter(SD_MUTEX(un));
30124 
30125 	switch (cmd) {
30126 	case SDIOCRUN:
30127 		/* Allow pushed faults to be injected */
30128 		SD_INFO(SD_LOG_SDTEST, un,
30129 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
30130 
30131 		sd_fault_injection_on = 1;
30132 
30133 		SD_INFO(SD_LOG_IOERR, un,
30134 		    "sd_faultinjection_ioctl: run finished\n");
30135 		break;
30136 
30137 	case SDIOCSTART:
30138 		/* Start Injection Session */
30139 		SD_INFO(SD_LOG_SDTEST, un,
30140 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
30141 
30142 		sd_fault_injection_on = 0;
30143 		un->sd_injection_mask = 0xFFFFFFFF;
30144 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30145 			un->sd_fi_fifo_pkt[i] = NULL;
30146 			un->sd_fi_fifo_xb[i] = NULL;
30147 			un->sd_fi_fifo_un[i] = NULL;
30148 			un->sd_fi_fifo_arq[i] = NULL;
30149 		}
30150 		un->sd_fi_fifo_start = 0;
30151 		un->sd_fi_fifo_end = 0;
30152 
30153 		mutex_enter(&(un->un_fi_mutex));
30154 		un->sd_fi_log[0] = '\0';
30155 		un->sd_fi_buf_len = 0;
30156 		mutex_exit(&(un->un_fi_mutex));
30157 
30158 		SD_INFO(SD_LOG_IOERR, un,
30159 		    "sd_faultinjection_ioctl: start finished\n");
30160 		break;
30161 
30162 	case SDIOCSTOP:
30163 		/* Stop Injection Session */
30164 		SD_INFO(SD_LOG_SDTEST, un,
30165 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
30166 		sd_fault_injection_on = 0;
30167 		un->sd_injection_mask = 0x0;
30168 
30169 		/* Empty stray or unuseds structs from fifo */
30170 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30171 			if (un->sd_fi_fifo_pkt[i] != NULL) {
30172 				kmem_free(un->sd_fi_fifo_pkt[i],
30173 				    sizeof (struct sd_fi_pkt));
30174 			}
30175 			if (un->sd_fi_fifo_xb[i] != NULL) {
30176 				kmem_free(un->sd_fi_fifo_xb[i],
30177 				    sizeof (struct sd_fi_xb));
30178 			}
30179 			if (un->sd_fi_fifo_un[i] != NULL) {
30180 				kmem_free(un->sd_fi_fifo_un[i],
30181 				    sizeof (struct sd_fi_un));
30182 			}
30183 			if (un->sd_fi_fifo_arq[i] != NULL) {
30184 				kmem_free(un->sd_fi_fifo_arq[i],
30185 				    sizeof (struct sd_fi_arq));
30186 			}
30187 			un->sd_fi_fifo_pkt[i] = NULL;
30188 			un->sd_fi_fifo_un[i] = NULL;
30189 			un->sd_fi_fifo_xb[i] = NULL;
30190 			un->sd_fi_fifo_arq[i] = NULL;
30191 		}
30192 		un->sd_fi_fifo_start = 0;
30193 		un->sd_fi_fifo_end = 0;
30194 
30195 		SD_INFO(SD_LOG_IOERR, un,
30196 		    "sd_faultinjection_ioctl: stop finished\n");
30197 		break;
30198 
30199 	case SDIOCINSERTPKT:
30200 		/* Store a packet struct to be pushed onto fifo */
30201 		SD_INFO(SD_LOG_SDTEST, un,
30202 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
30203 
30204 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30205 
30206 		sd_fault_injection_on = 0;
30207 
30208 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
30209 		if (un->sd_fi_fifo_pkt[i] != NULL) {
30210 			kmem_free(un->sd_fi_fifo_pkt[i],
30211 			    sizeof (struct sd_fi_pkt));
30212 		}
30213 		if (arg != NULL) {
30214 			un->sd_fi_fifo_pkt[i] =
30215 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
30216 			if (un->sd_fi_fifo_pkt[i] == NULL) {
30217 				/* Alloc failed don't store anything */
30218 				break;
30219 			}
30220 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
30221 			    sizeof (struct sd_fi_pkt), 0);
30222 			if (rval == -1) {
30223 				kmem_free(un->sd_fi_fifo_pkt[i],
30224 				    sizeof (struct sd_fi_pkt));
30225 				un->sd_fi_fifo_pkt[i] = NULL;
30226 			}
30227 		} else {
30228 			SD_INFO(SD_LOG_IOERR, un,
30229 			    "sd_faultinjection_ioctl: pkt null\n");
30230 		}
30231 		break;
30232 
30233 	case SDIOCINSERTXB:
30234 		/* Store a xb struct to be pushed onto fifo */
30235 		SD_INFO(SD_LOG_SDTEST, un,
30236 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
30237 
30238 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30239 
30240 		sd_fault_injection_on = 0;
30241 
30242 		if (un->sd_fi_fifo_xb[i] != NULL) {
30243 			kmem_free(un->sd_fi_fifo_xb[i],
30244 			    sizeof (struct sd_fi_xb));
30245 			un->sd_fi_fifo_xb[i] = NULL;
30246 		}
30247 		if (arg != NULL) {
30248 			un->sd_fi_fifo_xb[i] =
30249 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
30250 			if (un->sd_fi_fifo_xb[i] == NULL) {
30251 				/* Alloc failed don't store anything */
30252 				break;
30253 			}
30254 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
30255 			    sizeof (struct sd_fi_xb), 0);
30256 
30257 			if (rval == -1) {
30258 				kmem_free(un->sd_fi_fifo_xb[i],
30259 				    sizeof (struct sd_fi_xb));
30260 				un->sd_fi_fifo_xb[i] = NULL;
30261 			}
30262 		} else {
30263 			SD_INFO(SD_LOG_IOERR, un,
30264 			    "sd_faultinjection_ioctl: xb null\n");
30265 		}
30266 		break;
30267 
30268 	case SDIOCINSERTUN:
30269 		/* Store a un struct to be pushed onto fifo */
30270 		SD_INFO(SD_LOG_SDTEST, un,
30271 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
30272 
30273 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30274 
30275 		sd_fault_injection_on = 0;
30276 
30277 		if (un->sd_fi_fifo_un[i] != NULL) {
30278 			kmem_free(un->sd_fi_fifo_un[i],
30279 			    sizeof (struct sd_fi_un));
30280 			un->sd_fi_fifo_un[i] = NULL;
30281 		}
30282 		if (arg != NULL) {
30283 			un->sd_fi_fifo_un[i] =
30284 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
30285 			if (un->sd_fi_fifo_un[i] == NULL) {
30286 				/* Alloc failed don't store anything */
30287 				break;
30288 			}
30289 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
30290 			    sizeof (struct sd_fi_un), 0);
30291 			if (rval == -1) {
30292 				kmem_free(un->sd_fi_fifo_un[i],
30293 				    sizeof (struct sd_fi_un));
30294 				un->sd_fi_fifo_un[i] = NULL;
30295 			}
30296 
30297 		} else {
30298 			SD_INFO(SD_LOG_IOERR, un,
30299 			    "sd_faultinjection_ioctl: un null\n");
30300 		}
30301 
30302 		break;
30303 
30304 	case SDIOCINSERTARQ:
30305 		/* Store a arq struct to be pushed onto fifo */
30306 		SD_INFO(SD_LOG_SDTEST, un,
30307 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
30308 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30309 
30310 		sd_fault_injection_on = 0;
30311 
30312 		if (un->sd_fi_fifo_arq[i] != NULL) {
30313 			kmem_free(un->sd_fi_fifo_arq[i],
30314 			    sizeof (struct sd_fi_arq));
30315 			un->sd_fi_fifo_arq[i] = NULL;
30316 		}
30317 		if (arg != NULL) {
30318 			un->sd_fi_fifo_arq[i] =
30319 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
30320 			if (un->sd_fi_fifo_arq[i] == NULL) {
30321 				/* Alloc failed don't store anything */
30322 				break;
30323 			}
30324 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
30325 			    sizeof (struct sd_fi_arq), 0);
30326 			if (rval == -1) {
30327 				kmem_free(un->sd_fi_fifo_arq[i],
30328 				    sizeof (struct sd_fi_arq));
30329 				un->sd_fi_fifo_arq[i] = NULL;
30330 			}
30331 
30332 		} else {
30333 			SD_INFO(SD_LOG_IOERR, un,
30334 			    "sd_faultinjection_ioctl: arq null\n");
30335 		}
30336 
30337 		break;
30338 
30339 	case SDIOCPUSH:
30340 		/* Push stored xb, pkt, un, and arq onto fifo */
30341 		sd_fault_injection_on = 0;
30342 
30343 		if (arg != NULL) {
30344 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
30345 			if (rval != -1 &&
30346 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30347 				un->sd_fi_fifo_end += i;
30348 			}
30349 		} else {
30350 			SD_INFO(SD_LOG_IOERR, un,
30351 			    "sd_faultinjection_ioctl: push arg null\n");
30352 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30353 				un->sd_fi_fifo_end++;
30354 			}
30355 		}
30356 		SD_INFO(SD_LOG_IOERR, un,
30357 		    "sd_faultinjection_ioctl: push to end=%d\n",
30358 		    un->sd_fi_fifo_end);
30359 		break;
30360 
30361 	case SDIOCRETRIEVE:
30362 		/* Return buffer of log from Injection session */
30363 		SD_INFO(SD_LOG_SDTEST, un,
30364 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
30365 
30366 		sd_fault_injection_on = 0;
30367 
30368 		mutex_enter(&(un->un_fi_mutex));
30369 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
30370 		    un->sd_fi_buf_len+1, 0);
30371 		mutex_exit(&(un->un_fi_mutex));
30372 
30373 		if (rval == -1) {
30374 			/*
30375 			 * arg is possibly invalid setting
30376 			 * it to NULL for return
30377 			 */
30378 			arg = NULL;
30379 		}
30380 		break;
30381 	}
30382 
30383 	mutex_exit(SD_MUTEX(un));
30384 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
30385 			    " exit\n");
30386 }
30387 
30388 
30389 /*
30390  *    Function: sd_injection_log()
30391  *
30392  * Description: This routine adds buff to the already existing injection log
30393  *              for retrieval via faultinjection_ioctl for use in fault
30394  *              detection and recovery
30395  *
30396  *   Arguments: buf - the string to add to the log
30397  */
30398 
30399 static void
30400 sd_injection_log(char *buf, struct sd_lun *un)
30401 {
30402 	uint_t len;
30403 
30404 	ASSERT(un != NULL);
30405 	ASSERT(buf != NULL);
30406 
30407 	mutex_enter(&(un->un_fi_mutex));
30408 
30409 	len = min(strlen(buf), 255);
30410 	/* Add logged value to Injection log to be returned later */
30411 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30412 		uint_t	offset = strlen((char *)un->sd_fi_log);
30413 		char *destp = (char *)un->sd_fi_log + offset;
30414 		int i;
30415 		for (i = 0; i < len; i++) {
30416 			*destp++ = *buf++;
30417 		}
30418 		un->sd_fi_buf_len += len;
30419 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30420 	}
30421 
30422 	mutex_exit(&(un->un_fi_mutex));
30423 }
30424 
30425 
30426 /*
30427  *    Function: sd_faultinjection()
30428  *
30429  * Description: This routine takes the pkt and changes its
30430  *		content based on error injection scenerio.
30431  *
30432  *   Arguments: pktp	- packet to be changed
30433  */
30434 
30435 static void
30436 sd_faultinjection(struct scsi_pkt *pktp)
30437 {
30438 	uint_t i;
30439 	struct sd_fi_pkt *fi_pkt;
30440 	struct sd_fi_xb *fi_xb;
30441 	struct sd_fi_un *fi_un;
30442 	struct sd_fi_arq *fi_arq;
30443 	struct buf *bp;
30444 	struct sd_xbuf *xb;
30445 	struct sd_lun *un;
30446 
30447 	ASSERT(pktp != NULL);
30448 
30449 	/* pull bp xb and un from pktp */
30450 	bp = (struct buf *)pktp->pkt_private;
30451 	xb = SD_GET_XBUF(bp);
30452 	un = SD_GET_UN(bp);
30453 
30454 	ASSERT(un != NULL);
30455 
30456 	mutex_enter(SD_MUTEX(un));
30457 
30458 	SD_TRACE(SD_LOG_SDTEST, un,
30459 	    "sd_faultinjection: entry Injection from sdintr\n");
30460 
30461 	/* if injection is off return */
30462 	if (sd_fault_injection_on == 0 ||
30463 		un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30464 		mutex_exit(SD_MUTEX(un));
30465 		return;
30466 	}
30467 
30468 
30469 	/* take next set off fifo */
30470 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30471 
30472 	fi_pkt = un->sd_fi_fifo_pkt[i];
30473 	fi_xb = un->sd_fi_fifo_xb[i];
30474 	fi_un = un->sd_fi_fifo_un[i];
30475 	fi_arq = un->sd_fi_fifo_arq[i];
30476 
30477 
30478 	/* set variables accordingly */
30479 	/* set pkt if it was on fifo */
30480 	if (fi_pkt != NULL) {
30481 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30482 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30483 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30484 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30485 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30486 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30487 
30488 	}
30489 
30490 	/* set xb if it was on fifo */
30491 	if (fi_xb != NULL) {
30492 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30493 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30494 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30495 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30496 		    "xb_victim_retry_count");
30497 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30498 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30499 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30500 
30501 		/* copy in block data from sense */
30502 		if (fi_xb->xb_sense_data[0] != -1) {
30503 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30504 			    SENSE_LENGTH);
30505 		}
30506 
30507 		/* copy in extended sense codes */
30508 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
30509 		    "es_code");
30510 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
30511 		    "es_key");
30512 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
30513 		    "es_add_code");
30514 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
30515 		    es_qual_code, "es_qual_code");
30516 	}
30517 
30518 	/* set un if it was on fifo */
30519 	if (fi_un != NULL) {
30520 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30521 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30522 		SD_CONDSET(un, un, un_reset_retry_count,
30523 		    "un_reset_retry_count");
30524 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30525 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30526 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30527 		SD_CONDSET(un, un, un_f_geometry_is_valid,
30528 		    "un_f_geometry_is_valid");
30529 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30530 		    "un_f_allow_bus_device_reset");
30531 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30532 
30533 	}
30534 
30535 	/* copy in auto request sense if it was on fifo */
30536 	if (fi_arq != NULL) {
30537 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30538 	}
30539 
30540 	/* free structs */
30541 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30542 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30543 	}
30544 	if (un->sd_fi_fifo_xb[i] != NULL) {
30545 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30546 	}
30547 	if (un->sd_fi_fifo_un[i] != NULL) {
30548 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30549 	}
30550 	if (un->sd_fi_fifo_arq[i] != NULL) {
30551 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30552 	}
30553 
30554 	/*
30555 	 * kmem_free does not gurantee to set to NULL
30556 	 * since we uses these to determine if we set
30557 	 * values or not lets confirm they are always
30558 	 * NULL after free
30559 	 */
30560 	un->sd_fi_fifo_pkt[i] = NULL;
30561 	un->sd_fi_fifo_un[i] = NULL;
30562 	un->sd_fi_fifo_xb[i] = NULL;
30563 	un->sd_fi_fifo_arq[i] = NULL;
30564 
30565 	un->sd_fi_fifo_start++;
30566 
30567 	mutex_exit(SD_MUTEX(un));
30568 
30569 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30570 }
30571 
30572 #endif /* SD_FAULT_INJECTION */
30573 
30574 /*
30575  * This routine is invoked in sd_unit_attach(). Before calling it, the
30576  * properties in conf file should be processed already, and "hotpluggable"
30577  * property was processed also.
30578  *
30579  * The sd driver distinguishes 3 different type of devices: removable media,
30580  * non-removable media, and hotpluggable. Below the differences are defined:
30581  *
30582  * 1. Device ID
30583  *
30584  *     The device ID of a device is used to identify this device. Refer to
30585  *     ddi_devid_register(9F).
30586  *
30587  *     For a non-removable media disk device which can provide 0x80 or 0x83
30588  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30589  *     device ID is created to identify this device. For other non-removable
30590  *     media devices, a default device ID is created only if this device has
30591  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30592  *
30593  *     -------------------------------------------------------
30594  *     removable media   hotpluggable  | Can Have Device ID
30595  *     -------------------------------------------------------
30596  *         false             false     |     Yes
30597  *         false             true      |     Yes
30598  *         true                x       |     No
30599  *     ------------------------------------------------------
30600  *
30601  *
30602  * 2. SCSI group 4 commands
30603  *
30604  *     In SCSI specs, only some commands in group 4 command set can use
30605  *     8-byte addresses that can be used to access >2TB storage spaces.
30606  *     Other commands have no such capability. Without supporting group4,
30607  *     it is impossible to make full use of storage spaces of a disk with
30608  *     capacity larger than 2TB.
30609  *
30610  *     -----------------------------------------------
30611  *     removable media   hotpluggable   LP64  |  Group
30612  *     -----------------------------------------------
30613  *           false          false       false |   1
30614  *           false          false       true  |   4
30615  *           false          true        false |   1
30616  *           false          true        true  |   4
30617  *           true             x           x   |   5
30618  *     -----------------------------------------------
30619  *
30620  *
30621  * 3. Check for VTOC Label
30622  *
30623  *     If a direct-access disk has no EFI label, sd will check if it has a
30624  *     valid VTOC label. Now, sd also does that check for removable media
30625  *     and hotpluggable devices.
30626  *
30627  *     --------------------------------------------------------------
30628  *     Direct-Access   removable media    hotpluggable |  Check Label
30629  *     -------------------------------------------------------------
30630  *         false          false           false        |   No
30631  *         false          false           true         |   No
30632  *         false          true            false        |   Yes
30633  *         false          true            true         |   Yes
30634  *         true            x                x          |   Yes
30635  *     --------------------------------------------------------------
30636  *
30637  *
30638  * 4. Building default VTOC label
30639  *
30640  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30641  *     If those devices have no valid VTOC label, sd(7d) will attempt to
30642  *     create default VTOC for them. Currently sd creates default VTOC label
30643  *     for all devices on x86 platform (VTOC_16), but only for removable
30644  *     media devices on SPARC (VTOC_8).
30645  *
30646  *     -----------------------------------------------------------
30647  *       removable media hotpluggable platform   |   Default Label
30648  *     -----------------------------------------------------------
30649  *             false          false    sparc     |     No
30650  *             false          true      x86      |     Yes
30651  *             false          true     sparc     |     Yes
30652  *             true             x        x       |     Yes
30653  *     ----------------------------------------------------------
30654  *
30655  *
30656  * 5. Supported blocksizes of target devices
30657  *
30658  *     Sd supports non-512-byte blocksize for removable media devices only.
30659  *     For other devices, only 512-byte blocksize is supported. This may be
30660  *     changed in near future because some RAID devices require non-512-byte
30661  *     blocksize
30662  *
30663  *     -----------------------------------------------------------
30664  *     removable media    hotpluggable    | non-512-byte blocksize
30665  *     -----------------------------------------------------------
30666  *           false          false         |   No
30667  *           false          true          |   No
30668  *           true             x           |   Yes
30669  *     -----------------------------------------------------------
30670  *
30671  *
30672  * 6. Automatic mount & unmount (i.e. vold)
30673  *
30674  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30675  *     if a device is removable media device. It return 1 for removable media
30676  *     devices, and 0 for others.
30677  *
30678  *     Vold treats a device as removable one only if DKIOREMOVABLE returns 1.
30679  *     And it does automounting only for removable media devices. In order to
30680  *     preserve users' experience and let vold continue to do automounting for
30681  *     USB disk devices, DKIOCREMOVABLE ioctl still returns 1 for USB/1394 disk
30682  *     devices.
30683  *
30684  *      ------------------------------------------------------
30685  *       removable media    hotpluggable   |  automatic mount
30686  *      ------------------------------------------------------
30687  *             false          false        |   No
30688  *             false          true         |   Yes
30689  *             true             x          |   Yes
30690  *      ------------------------------------------------------
30691  *
30692  *
30693  * 7. fdisk partition management
30694  *
30695  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
30696  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30697  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
30698  *     fdisk partitions on both x86 and SPARC platform.
30699  *
30700  *     -----------------------------------------------------------
30701  *       platform   removable media  USB/1394  |  fdisk supported
30702  *     -----------------------------------------------------------
30703  *        x86         X               X        |       true
30704  *     ------------------------------------------------------------
30705  *        sparc       X               X        |       false
30706  *     ------------------------------------------------------------
30707  *
30708  *
30709  * 8. MBOOT/MBR
30710  *
30711  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
30712  *     read/write mboot for removable media devices on sparc platform.
30713  *
30714  *     -----------------------------------------------------------
30715  *       platform   removable media  USB/1394  |  mboot supported
30716  *     -----------------------------------------------------------
30717  *        x86         X               X        |       true
30718  *     ------------------------------------------------------------
30719  *        sparc      false           false     |       false
30720  *        sparc      false           true      |       true
30721  *        sparc      true            false     |       true
30722  *        sparc      true            true      |       true
30723  *     ------------------------------------------------------------
30724  *
30725  *
30726  * 9.  error handling during opening device
30727  *
30728  *     If failed to open a disk device, an errno is returned. For some kinds
30729  *     of errors, different errno is returned depending on if this device is
30730  *     a removable media device. This brings USB/1394 hard disks in line with
30731  *     expected hard disk behavior. It is not expected that this breaks any
30732  *     application.
30733  *
30734  *     ------------------------------------------------------
30735  *       removable media    hotpluggable   |  errno
30736  *     ------------------------------------------------------
30737  *             false          false        |   EIO
30738  *             false          true         |   EIO
30739  *             true             x          |   ENXIO
30740  *     ------------------------------------------------------
30741  *
30742  *
30743  * 10. off-by-1 workaround (bug 1175930, and 4996920) (x86 only)
30744  *
30745  *     [ this is a bit of very ugly history, soon to be removed ]
30746  *
30747  *     SCSI READ_CAPACITY command returns the last valid logical block number
30748  *     which starts from 0. So real capacity is larger than the returned
30749  *     value by 1. However, because scdk.c (which was EOL'ed) directly used
30750  *     the logical block number as capacity of disk devices, off-by-1 work-
30751  *     around was applied. This workaround causes fixed SCSI disk to loss a
30752  *     sector on x86 platform, and precludes exchanging fixed hard disks
30753  *     between sparc and x86.
30754  *
30755  *     ------------------------------------------------------
30756  *       removable media    hotplug        |   Off-by-1 works
30757  *     -------------------------------------------------------
30758  *             false          false        |     Yes
30759  *             false          true         |     No
30760  *             true           false        |     No
30761  *             true           true         |     No
30762  *     ------------------------------------------------------
30763  *
30764  *
30765  * 11. ioctls: DKIOCEJECT, CDROMEJECT
30766  *
30767  *     These IOCTLs are applicable only to removable media devices.
30768  *
30769  *     -----------------------------------------------------------
30770  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
30771  *     -----------------------------------------------------------
30772  *             false          false        |     No
30773  *             false          true         |     No
30774  *             true            x           |     Yes
30775  *     -----------------------------------------------------------
30776  *
30777  *
30778  * 12. Kstats for partitions
30779  *
30780  *     sd creates partition kstat for non-removable media devices. USB and
30781  *     Firewire hard disks now have partition kstats
30782  *
30783  *      ------------------------------------------------------
30784  *       removable media    hotplugable    |   kstat
30785  *      ------------------------------------------------------
30786  *             false          false        |    Yes
30787  *             false          true         |    Yes
30788  *             true             x          |    No
30789  *       ------------------------------------------------------
30790  *
30791  *
30792  * 13. Removable media & hotpluggable properties
30793  *
30794  *     Sd driver creates a "removable-media" property for removable media
30795  *     devices. Parent nexus drivers create a "hotpluggable" property if
30796  *     it supports hotplugging.
30797  *
30798  *     ---------------------------------------------------------------------
30799  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
30800  *     ---------------------------------------------------------------------
30801  *       false            false       |    No                   No
30802  *       false            true        |    No                   Yes
30803  *       true             false       |    Yes                  No
30804  *       true             true        |    Yes                  Yes
30805  *     ---------------------------------------------------------------------
30806  *
30807  *
30808  * 14. Power Management
30809  *
30810  *     sd only power manages removable media devices or devices that support
30811  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
30812  *
30813  *     A parent nexus that supports hotplugging can also set "pm-capable"
30814  *     if the disk can be power managed.
30815  *
30816  *     ------------------------------------------------------------
30817  *       removable media hotpluggable pm-capable  |   power manage
30818  *     ------------------------------------------------------------
30819  *             false          false     false     |     No
30820  *             false          false     true      |     Yes
30821  *             false          true      false     |     No
30822  *             false          true      true      |     Yes
30823  *             true             x        x        |     Yes
30824  *     ------------------------------------------------------------
30825  *
30826  *      USB and firewire hard disks can now be power managed independently
30827  *      of the framebuffer
30828  *
30829  *
30830  * 15. Support for USB disks with capacity larger than 1TB
30831  *
30832  *     Currently, sd doesn't permit a fixed disk device with capacity
30833  *     larger than 1TB to be used in a 32-bit operating system environment.
30834  *     However, sd doesn't do that for removable media devices. Instead, it
30835  *     assumes that removable media devices cannot have a capacity larger
30836  *     than 1TB. Therefore, using those devices on 32-bit system is partially
30837  *     supported, which can cause some unexpected results.
30838  *
30839  *     ---------------------------------------------------------------------
30840  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
30841  *     ---------------------------------------------------------------------
30842  *             false          false  |   true         |     no
30843  *             false          true   |   true         |     no
30844  *             true           false  |   true         |     Yes
30845  *             true           true   |   true         |     Yes
30846  *     ---------------------------------------------------------------------
30847  *
30848  *
30849  * 16. Check write-protection at open time
30850  *
30851  *     When a removable media device is being opened for writing without NDELAY
30852  *     flag, sd will check if this device is writable. If attempting to open
30853  *     without NDELAY flag a write-protected device, this operation will abort.
30854  *
30855  *     ------------------------------------------------------------
30856  *       removable media    USB/1394   |   WP Check
30857  *     ------------------------------------------------------------
30858  *             false          false    |     No
30859  *             false          true     |     No
30860  *             true           false    |     Yes
30861  *             true           true     |     Yes
30862  *     ------------------------------------------------------------
30863  *
30864  *
30865  * 17. syslog when corrupted VTOC is encountered
30866  *
30867  *      Currently, if an invalid VTOC is encountered, sd only print syslog
30868  *      for fixed SCSI disks.
30869  *     ------------------------------------------------------------
30870  *       removable media    USB/1394   |   print syslog
30871  *     ------------------------------------------------------------
30872  *             false          false    |     Yes
30873  *             false          true     |     No
30874  *             true           false    |     No
30875  *             true           true     |     No
30876  *     ------------------------------------------------------------
30877  */
30878 static void
30879 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
30880 {
30881 	int	pm_capable_prop;
30882 
30883 	ASSERT(un->un_sd);
30884 	ASSERT(un->un_sd->sd_inq);
30885 
30886 #if defined(_SUNOS_VTOC_16)
30887 	/*
30888 	 * For VTOC_16 devices, the default label will be created for all
30889 	 * devices. (see sd_build_default_label)
30890 	 */
30891 	un->un_f_default_vtoc_supported = TRUE;
30892 #endif
30893 
30894 	if (un->un_sd->sd_inq->inq_rmb) {
30895 		/*
30896 		 * The media of this device is removable. And for this kind
30897 		 * of devices, it is possible to change medium after openning
30898 		 * devices. Thus we should support this operation.
30899 		 */
30900 		un->un_f_has_removable_media = TRUE;
30901 
30902 #if defined(_SUNOS_VTOC_8)
30903 		/*
30904 		 * Note: currently, for VTOC_8 devices, default label is
30905 		 * created for removable and hotpluggable devices only.
30906 		 */
30907 		un->un_f_default_vtoc_supported = TRUE;
30908 #endif
30909 		/*
30910 		 * support non-512-byte blocksize of removable media devices
30911 		 */
30912 		un->un_f_non_devbsize_supported = TRUE;
30913 
30914 		/*
30915 		 * Assume that all removable media devices support DOOR_LOCK
30916 		 */
30917 		un->un_f_doorlock_supported = TRUE;
30918 
30919 		/*
30920 		 * For a removable media device, it is possible to be opened
30921 		 * with NDELAY flag when there is no media in drive, in this
30922 		 * case we don't care if device is writable. But if without
30923 		 * NDELAY flag, we need to check if media is write-protected.
30924 		 */
30925 		un->un_f_chk_wp_open = TRUE;
30926 
30927 		/*
30928 		 * need to start a SCSI watch thread to monitor media state,
30929 		 * when media is being inserted or ejected, notify syseventd.
30930 		 */
30931 		un->un_f_monitor_media_state = TRUE;
30932 
30933 		/*
30934 		 * Some devices don't support START_STOP_UNIT command.
30935 		 * Therefore, we'd better check if a device supports it
30936 		 * before sending it.
30937 		 */
30938 		un->un_f_check_start_stop = TRUE;
30939 
30940 		/*
30941 		 * support eject media ioctl:
30942 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
30943 		 */
30944 		un->un_f_eject_media_supported = TRUE;
30945 
30946 		/*
30947 		 * Because many removable-media devices don't support
30948 		 * LOG_SENSE, we couldn't use this command to check if
30949 		 * a removable media device support power-management.
30950 		 * We assume that they support power-management via
30951 		 * START_STOP_UNIT command and can be spun up and down
30952 		 * without limitations.
30953 		 */
30954 		un->un_f_pm_supported = TRUE;
30955 
30956 		/*
30957 		 * Need to create a zero length (Boolean) property
30958 		 * removable-media for the removable media devices.
30959 		 * Note that the return value of the property is not being
30960 		 * checked, since if unable to create the property
30961 		 * then do not want the attach to fail altogether. Consistent
30962 		 * with other property creation in attach.
30963 		 */
30964 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
30965 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
30966 
30967 	} else {
30968 		/*
30969 		 * create device ID for device
30970 		 */
30971 		un->un_f_devid_supported = TRUE;
30972 
30973 		/*
30974 		 * Spin up non-removable-media devices once it is attached
30975 		 */
30976 		un->un_f_attach_spinup = TRUE;
30977 
30978 		/*
30979 		 * According to SCSI specification, Sense data has two kinds of
30980 		 * format: fixed format, and descriptor format. At present, we
30981 		 * don't support descriptor format sense data for removable
30982 		 * media.
30983 		 */
30984 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
30985 			un->un_f_descr_format_supported = TRUE;
30986 		}
30987 
30988 		/*
30989 		 * kstats are created only for non-removable media devices.
30990 		 *
30991 		 * Set this in sd.conf to 0 in order to disable kstats.  The
30992 		 * default is 1, so they are enabled by default.
30993 		 */
30994 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
30995 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
30996 			"enable-partition-kstats", 1));
30997 
30998 		/*
30999 		 * Check if HBA has set the "pm-capable" property.
31000 		 * If "pm-capable" exists and is non-zero then we can
31001 		 * power manage the device without checking the start/stop
31002 		 * cycle count log sense page.
31003 		 *
31004 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
31005 		 * then we should not power manage the device.
31006 		 *
31007 		 * If "pm-capable" doesn't exist then pm_capable_prop will
31008 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
31009 		 * sd will check the start/stop cycle count log sense page
31010 		 * and power manage the device if the cycle count limit has
31011 		 * not been exceeded.
31012 		 */
31013 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
31014 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
31015 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
31016 			un->un_f_log_sense_supported = TRUE;
31017 		} else {
31018 			/*
31019 			 * pm-capable property exists.
31020 			 *
31021 			 * Convert "TRUE" values for pm_capable_prop to
31022 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
31023 			 * later. "TRUE" values are any values except
31024 			 * SD_PM_CAPABLE_FALSE (0) and
31025 			 * SD_PM_CAPABLE_UNDEFINED (-1)
31026 			 */
31027 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
31028 				un->un_f_log_sense_supported = FALSE;
31029 			} else {
31030 				un->un_f_pm_supported = TRUE;
31031 			}
31032 
31033 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
31034 			    "sd_unit_attach: un:0x%p pm-capable "
31035 			    "property set to %d.\n", un, un->un_f_pm_supported);
31036 		}
31037 	}
31038 
31039 	if (un->un_f_is_hotpluggable) {
31040 #if defined(_SUNOS_VTOC_8)
31041 		/*
31042 		 * Note: currently, for VTOC_8 devices, default label is
31043 		 * created for removable and hotpluggable devices only.
31044 		 */
31045 		un->un_f_default_vtoc_supported = TRUE;
31046 #endif
31047 
31048 		/*
31049 		 * Temporarily, let hotpluggable devices pretend to be
31050 		 * removable-media devices for vold.
31051 		 */
31052 		un->un_f_monitor_media_state = TRUE;
31053 
31054 		un->un_f_check_start_stop = TRUE;
31055 
31056 	}
31057 
31058 	/*
31059 	 * By default, only DIRECT ACCESS devices and CDs will have Sun
31060 	 * labels.
31061 	 */
31062 	if ((SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) ||
31063 	    (un->un_sd->sd_inq->inq_rmb)) {
31064 		/*
31065 		 * Direct access devices have disk label
31066 		 */
31067 		un->un_f_vtoc_label_supported = TRUE;
31068 	}
31069 
31070 	/*
31071 	 * Fdisk partitions are supported for all direct access devices on
31072 	 * x86 platform, and just for removable media and hotpluggable
31073 	 * devices on SPARC platform. Later, we will set the following flag
31074 	 * to FALSE if current device is not removable media or hotpluggable
31075 	 * device and if sd works on SAPRC platform.
31076 	 */
31077 	if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
31078 		un->un_f_mboot_supported = TRUE;
31079 	}
31080 
31081 	if (!un->un_f_is_hotpluggable &&
31082 	    !un->un_sd->sd_inq->inq_rmb) {
31083 
31084 #if defined(_SUNOS_VTOC_8)
31085 		/*
31086 		 * Don't support fdisk on fixed disk
31087 		 */
31088 		un->un_f_mboot_supported = FALSE;
31089 #endif
31090 
31091 		/*
31092 		 * Fixed disk support SYNC CACHE
31093 		 */
31094 		un->un_f_sync_cache_supported = TRUE;
31095 
31096 		/*
31097 		 * For fixed disk, if its VTOC is not valid, we will write
31098 		 * errlog into system log
31099 		 */
31100 		if (un->un_f_vtoc_label_supported)
31101 			un->un_f_vtoc_errlog_supported = TRUE;
31102 	}
31103 }
31104