xref: /illumos-gate/usr/src/uts/common/io/scsi/impl/scsi_hba.c (revision 3d393ee6c37fa10ac512ed6d36109ad616dc7c1a)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/note.h>
27 
28 /*
29  * Generic SCSI Host Bus Adapter interface implementation
30  */
31 #include <sys/scsi/scsi.h>
32 #include <sys/file.h>
33 #include <sys/ddi_impldefs.h>
34 #include <sys/ndi_impldefs.h>
35 #include <sys/ddi.h>
36 #include <sys/epm.h>
37 
38 extern struct scsi_pkt *scsi_init_cache_pkt(struct scsi_address *,
39 		    struct scsi_pkt *, struct buf *, int, int, int, int,
40 		    int (*)(caddr_t), caddr_t);
41 extern void scsi_free_cache_pkt(struct scsi_address *,
42 		    struct scsi_pkt *);
43 extern void scsi_cache_dmafree(struct scsi_address *,
44 		    struct scsi_pkt *);
45 extern void scsi_sync_cache_pkt(struct scsi_address *,
46 		    struct scsi_pkt *);
47 
48 /*
49  * Round up all allocations so that we can guarantee
50  * long-long alignment.  This is the same alignment
51  * provided by kmem_alloc().
52  */
53 #define	ROUNDUP(x)	(((x) + 0x07) & ~0x07)
54 
55 /* Magic number to track correct allocations in wrappers */
56 #define	PKT_WRAPPER_MAGIC	0xa110ced	/* alloced correctly */
57 
58 kmutex_t	scsi_flag_nointr_mutex;
59 kcondvar_t	scsi_flag_nointr_cv;
60 kmutex_t	scsi_log_mutex;
61 
62 /*
63  * Prototypes for static functions
64  */
65 static int	scsi_hba_bus_ctl(
66 			dev_info_t		*self,
67 			dev_info_t		*child,
68 			ddi_ctl_enum_t		op,
69 			void			*arg,
70 			void			*result);
71 
72 static int	scsi_hba_map_fault(
73 			dev_info_t		*self,
74 			dev_info_t		*child,
75 			struct hat		*hat,
76 			struct seg		*seg,
77 			caddr_t			addr,
78 			struct devpage		*dp,
79 			pfn_t			pfn,
80 			uint_t			prot,
81 			uint_t			lock);
82 
83 static int	scsi_hba_get_eventcookie(
84 			dev_info_t		*self,
85 			dev_info_t		*child,
86 			char			*name,
87 			ddi_eventcookie_t	*eventp);
88 
89 static int	scsi_hba_add_eventcall(
90 			dev_info_t		*self,
91 			dev_info_t		*child,
92 			ddi_eventcookie_t	event,
93 			void			(*callback)(
94 				dev_info_t		*dip,
95 				ddi_eventcookie_t	event,
96 				void			*arg,
97 				void			*bus_impldata),
98 			void			*arg,
99 			ddi_callback_id_t	*cb_id);
100 
101 static int	scsi_hba_remove_eventcall(
102 			dev_info_t		*self,
103 			ddi_callback_id_t	id);
104 
105 static int	scsi_hba_post_event(
106 			dev_info_t		*self,
107 			dev_info_t		*child,
108 			ddi_eventcookie_t	event,
109 			void			*bus_impldata);
110 
111 static int	scsi_hba_info(
112 			dev_info_t		*self,
113 			ddi_info_cmd_t		infocmd,
114 			void			*arg,
115 			void			**result);
116 
117 static int	scsi_hba_bus_config(
118 			dev_info_t		*self,
119 			uint_t			flags,
120 			ddi_bus_config_op_t	op,
121 			void			*arg,
122 			dev_info_t		**childp);
123 
124 static int	scsi_hba_bus_unconfig(
125 			dev_info_t		*self,
126 			uint_t			flags,
127 			ddi_bus_config_op_t	op,
128 			void			*arg);
129 
130 static int	scsi_hba_fm_init_child(
131 			dev_info_t		*self,
132 			dev_info_t		*child,
133 			int			cap,
134 			ddi_iblock_cookie_t	*ibc);
135 
136 static int scsi_hba_bus_power(
137 			dev_info_t		*self,
138 			void			*impl_arg,
139 			pm_bus_power_op_t	op,
140 			void			*arg,
141 			void			*result);
142 
143 /* busops vector for SCSI HBA's. */
144 static struct bus_ops scsi_hba_busops = {
145 	BUSO_REV,
146 	nullbusmap,			/* bus_map */
147 	NULL,				/* bus_get_intrspec */
148 	NULL,				/* bus_add_intrspec */
149 	NULL,				/* bus_remove_intrspec */
150 	scsi_hba_map_fault,		/* bus_map_fault */
151 	ddi_dma_map,			/* bus_dma_map */
152 	ddi_dma_allochdl,		/* bus_dma_allochdl */
153 	ddi_dma_freehdl,		/* bus_dma_freehdl */
154 	ddi_dma_bindhdl,		/* bus_dma_bindhdl */
155 	ddi_dma_unbindhdl,		/* bus_unbindhdl */
156 	ddi_dma_flush,			/* bus_dma_flush */
157 	ddi_dma_win,			/* bus_dma_win */
158 	ddi_dma_mctl,			/* bus_dma_ctl */
159 	scsi_hba_bus_ctl,		/* bus_ctl */
160 	ddi_bus_prop_op,		/* bus_prop_op */
161 	scsi_hba_get_eventcookie,	/* bus_get_eventcookie */
162 	scsi_hba_add_eventcall,		/* bus_add_eventcall */
163 	scsi_hba_remove_eventcall,	/* bus_remove_eventcall */
164 	scsi_hba_post_event,		/* bus_post_event */
165 	NULL,				/* bus_intr_ctl */
166 	scsi_hba_bus_config,		/* bus_config */
167 	scsi_hba_bus_unconfig,		/* bus_unconfig */
168 	scsi_hba_fm_init_child,		/* bus_fm_init */
169 	NULL,				/* bus_fm_fini */
170 	NULL,				/* bus_fm_access_enter */
171 	NULL,				/* bus_fm_access_exit */
172 	scsi_hba_bus_power		/* bus_power */
173 };
174 
175 /* cb_ops for hotplug :devctl and :scsi support */
176 static struct cb_ops scsi_hba_cbops = {
177 	scsi_hba_open,
178 	scsi_hba_close,
179 	nodev,			/* strategy */
180 	nodev,			/* print */
181 	nodev,			/* dump */
182 	nodev,			/* read */
183 	nodev,			/* write */
184 	scsi_hba_ioctl,		/* ioctl */
185 	nodev,			/* devmap */
186 	nodev,			/* mmap */
187 	nodev,			/* segmap */
188 	nochpoll,		/* poll */
189 	ddi_prop_op,		/* prop_op */
190 	NULL,			/* stream */
191 	D_NEW|D_MP|D_HOTPLUG,	/* cb_flag */
192 	CB_REV,			/* rev */
193 	nodev,			/* int (*cb_aread)() */
194 	nodev			/* int (*cb_awrite)() */
195 };
196 
197 /*
198  * SCSI_HBA_LOG is used for all messages. Both a logging level and a component
199  * are specified when generating a message. Some levels correspond directly to
200  * cmn_err levels, the others are associated with increasing levels diagnostic.
201  * The component is used to identify groups of messages by utility, typically
202  * the entry point. Filtering is provided for both the level and component.
203  * Messages with cmn_err levels or not associated with a component
204  * (SCSI_HBA_LOG_NC) are never filtered.
205  *
206  * For debugging, more complete information can be displayed with each message
207  * (full device path and pointer values).
208  */
209 /* logging levels */
210 #define	SCSI_HBA_LOGCONT	CE_CONT
211 #define	SCSI_HBA_LOGNOTE	CE_NOTE
212 #define	SCSI_HBA_LOGWARN	CE_WARN
213 #define	SCSI_HBA_LOGPANIC	CE_PANIC
214 #define	SCSI_HBA_LOGIGNORE	CE_IGNORE
215 #define	SCSI_HBA_LOG_CE_MASK	0x0000000F	/* no filter */
216 #define	SCSI_HBA_LOGDIAG1	0x00000010
217 #define	SCSI_HBA_LOGDIAG2	0x00000020
218 #define	SCSI_HBA_LOGDIAG3	0x00000040
219 #define	SCSI_HBA_LOGDIAG4	0x00000080
220 #define	SCSI_HBA_LOGTRACE	0x00000100
221 #if (CE_CONT | CE_NOTE | CE_WARN | CE_PANIC | CE_IGNORE) > SCSI_HBA_LOG_CE_MASK
222 Error, problem with CE_ definitions
223 #endif
224 
225 /* logging components */
226 #define	SCSI_HBA_LOG_NC				0x00000000 /* no filter */
227 #define	SCSI_HBA_LOG_INITIALIZE_HBA_INTERFACE	0x00000001
228 #define	SCSI_HBA_LOG_ATTACH_SETUP		0x00000002
229 #define	SCSI_HBA_LOG_BUS_CTL			0x00000004
230 
231 #define	SCSI_HBA_LOG_BUS_CONFIG			0x00000010
232 #define	SCSI_HBA_LOG_BUS_CONFIGONE		0x00000020
233 #define	SCSI_HBA_LOG_BUS_CONFIGALL_SPI		0x00000040
234 #define	SCSI_HBA_LOG_ENUM_LUNS_ON_TGT		0x00000080
235 
236 #define	SCSI_HBA_LOG_DEVICE_REPORTLUNS		0x00000100
237 #define	SCSI_HBA_LOG_DEVICE_CONFIG		0x00000200
238 #define	SCSI_HBA_LOG_DEVICE_CONFIGCHILD		0x00000400
239 #define	SCSI_HBA_LOG_DEVICE_CREATECHILD		0x00000800
240 
241 #define	SCSI_HBA_LOG_DEVICE_INITCHILD		0x00001000
242 
243 #define	SCSI_HBA_LOG_BUS_UNCONFIG		0x00010000
244 #define	SCSI_HBA_LOG_BUS_UNCONFIGONE		0x00020000
245 #define	SCSI_HBA_LOG_BUS_UNCONFIGALL_SPI	0x00040000
246 #define	SCSI_HBA_LOG_DEVICE_UNINITCHILD		0x00080000
247 
248 #define	SCSI_HBA_LOG_REMOVE_NODE		0x00100000
249 
250 #define	SCSI_HBA_LOG_MSCSI_BUS_CONFIG_PORT	0x01000000
251 #define	SCSI_HBA_LOG_MSCSI_DEFINE_PORT		0x02000000
252 
253 #define	SCSI_HBA_LOG_BADLUN			0x10000000
254 #define	SCSI_HBA_LOG_PKT_ALLOC			0x20000000
255 #define	SCSI_HBA_LOG_DEVI_FIND			0x40000000
256 
257 
258 #define	SCSI_HBA_LOG_ASCII {			\
259 	"scsi_hba_initialize_hba_interface",	\
260 	"scsi_hba_attach_setup",		\
261 	"scsi_hba_bus_ctl",			\
262 	"-",					\
263 						\
264 	"scsi_hba_bus_config",			\
265 	"scsi_hba_bus_configone",		\
266 	"scsi_hba_bus_configall_spi",		\
267 	"scsi_hba_enum_luns_on_tgt",		\
268 						\
269 	"scsi_hba_device_reportluns",		\
270 	"scsi_hba_device_config",		\
271 	"scsi_hba_device_configchild",		\
272 	"scsi_hba_device_createchild",		\
273 						\
274 	"scsi_busctl_initchild",		\
275 	"-",					\
276 	"-",					\
277 	"-",					\
278 						\
279 	"scsi_hba_bus_unconfig",		\
280 	"scsi_hba_bus_unconfigone",		\
281 	"scsi_hba_bus_unconfigall_spi",		\
282 	"scsi_busctl_uninitchild",		\
283 						\
284 	"scsi_hba_remove_node",			\
285 	"-",					\
286 	"-",					\
287 	"-",					\
288 						\
289 	"scsi_hba_mscsi_bus_config_port",	\
290 	"scsi_hba_mscsi_define_port",		\
291 	"-",					\
292 	"-",					\
293 						\
294 	"scsi_hba_badlun",			\
295 	"scsi_hba_pkt_alloc",			\
296 	"scsi_hba_devi_find",			\
297 	NULL }
298 
299 /*
300  * Tunable log message augmentation and filters: filters do not apply to
301  * SCSI_HBA_LOG_CE_MASK level or SCSI_HBA_LOG_NC component messages.
302  *
303  * An example set of /etc/system tunings to debug a SCSA HBA driver called
304  * "fp" might be:
305  *	echo "set scsi:scsi_hba_log_filter_level=0xff"	>> /etc/system
306  *	echo "set scsi:scsi_hba_log_filter_hba=\"fp\""	>> /etc/system
307  *	echo "set scsi:scsi_hba_log_info=0x5"		>> /etc/system
308  *	echo "set scsi:scsi_hba_log_mt_disable=0x6"	>> /etc/system
309  */
310 int		scsi_hba_log_filter_level =
311 			SCSI_HBA_LOGDIAG1 |
312 			0;
313 int		scsi_hba_log_filter_component =
314 			-1;		/* all components */
315 char		*scsi_hba_log_filter_hba = "\0\0\0\0\0\0\0\0\0\0\0\0";
316 int		scsi_hba_log_info =	/* augmentation: extra info to print */
317 			(0 << 0) |	/* 0x0001: process information */
318 			(0 << 1) |	/* 0x0002: full devices path */
319 			(0 << 2);	/* 0x0004: devinfo pointer */
320 int		scsi_hba_log_mt_disable =
321 			/* SCSI_ENUMERATION_MT_LUN_DISABLE | */
322 			/* SCSI_ENUMERATION_MT_TARGET_DISABLE | */
323 			0;
324 
325 /* static data for HBA logging subsystem */
326 static kmutex_t	scsi_hba_log_mutex;
327 static char	scsi_hba_log_i[512];
328 static char	scsi_hba_log_buf[512];
329 static char	scsi_hba_fmt[64];
330 static char	*scsi_hba_log_lab[] = SCSI_HBA_LOG_ASCII;
331 
332 /* Macros to use in source code */
333 #define	_LOG(level, component)	SCSI_HBA_LOG##level, SCSI_HBA_LOG_##component
334 #define	SCSI_HBA_LOG(x)	scsi_hba_log x
335 
336 /*PRINTFLIKE5*/
337 void
338 scsi_hba_log(int level, int component,
339     dev_info_t *self, dev_info_t *child, const char *fmt, ...)
340 {
341 	va_list		ap;
342 	int		clevel;
343 	char		*info;
344 	char		*clabel;
345 	char		*f;
346 	int		i;
347 
348 	/* derive self from child's parent */
349 	if ((self == NULL) && child)
350 		self = ddi_get_parent(child);
351 
352 	/* always allow filtering on TRACE calls */
353 	if ((level & SCSI_HBA_LOGTRACE) &&
354 	    ((scsi_hba_log_filter_level & SCSI_HBA_LOGTRACE) == 0))
355 		return;
356 
357 	/* no filtering of SCSI_HBA_LOG_CE_MASK or NC messages */
358 	if (((level & SCSI_HBA_LOG_CE_MASK) != level) &&
359 	    (component != SCSI_HBA_LOG_NC)) {
360 		/* filter on level */
361 		if ((level & scsi_hba_log_filter_level) == 0)
362 			return;
363 
364 		/* filter on component */
365 		if ((component & scsi_hba_log_filter_component) == 0)
366 			return;
367 
368 		/* filter on self */
369 		if (self && scsi_hba_log_filter_hba &&
370 		    *scsi_hba_log_filter_hba &&
371 		    ((ddi_driver_name(self) == NULL) ||
372 		    strcmp(ddi_driver_name(self), scsi_hba_log_filter_hba)))
373 			return;
374 	}
375 
376 
377 	/* determine the cmn_err form */
378 	clevel = ((level & SCSI_HBA_LOG_CE_MASK) == level) ? level : CE_CONT;
379 
380 	/* determine the component label, SCSI_HBA_LOG_NC has none */
381 	clabel = NULL;
382 	for (i = 0; scsi_hba_log_lab[i]; i++) {
383 		if (component & (1 << i)) {
384 			clabel = scsi_hba_log_lab[i];
385 			break;
386 		}
387 	}
388 
389 	if ((clabel == NULL) && (level & SCSI_HBA_LOGTRACE))
390 		clabel = "trace";
391 
392 	mutex_enter(&scsi_hba_log_mutex);
393 
394 	/* skip special first characters, we add them back below */
395 	f = (char *)fmt;
396 	if (*f && strchr("^!?", *f))
397 		f++;
398 	va_start(ap, fmt);
399 	(void) vsprintf(scsi_hba_log_buf, f, ap);
400 	va_end(ap);
401 
402 	/* augment message */
403 	info = scsi_hba_log_i;
404 	*info = '\0';
405 	if ((scsi_hba_log_info & 0x0001) && curproc && PTOU(curproc)->u_comm) {
406 		(void) sprintf(info, "%s[%d]%p ",
407 		    PTOU(curproc)->u_comm, curproc->p_pid, (void *)curthread);
408 		info += strlen(info);
409 	}
410 	if (self) {
411 		if ((scsi_hba_log_info & 0x0004) && (child || self)) {
412 			(void) sprintf(info, "%p ",
413 			    (void *)(child ? child : self));
414 			info += strlen(info);
415 		}
416 		if (scsi_hba_log_info & 0x0002)	{
417 			(void) ddi_pathname(child ? child : self, info);
418 			(void) strcat(info, " ");
419 			info += strlen(info);
420 		} else {
421 			(void) sprintf(info, "%s%d: ",
422 			    ddi_driver_name(self), ddi_get_instance(self));
423 			info += strlen(info);
424 			if (child) {
425 				if (i_ddi_node_state(child) < DS_INITIALIZED)
426 					(void) sprintf(info, "%s ",
427 					    ddi_node_name(child));
428 				else
429 					(void) sprintf(info, "%s@%s ",
430 					    ddi_node_name(child),
431 					    ddi_get_name_addr(child));
432 				info += strlen(info);
433 			}
434 		}
435 	}
436 
437 	/* special first characters must be in format string itself */
438 	f = scsi_hba_fmt;
439 	if (fmt[0] && strchr("^!?", fmt[0]))
440 		*f++ = fmt[0];
441 	(void) sprintf(f, "%s", clabel ? "%s: %s%s%s" : "%s%s%s");
442 	if (clabel)
443 		cmn_err(clevel, scsi_hba_fmt, clabel, scsi_hba_log_i,
444 		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
445 	else
446 		cmn_err(clevel, scsi_hba_fmt, scsi_hba_log_i,
447 		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
448 	mutex_exit(&scsi_hba_log_mutex);
449 }
450 
451 /*
452  * Called from _init() when loading "scsi" module
453  */
454 void
455 scsi_initialize_hba_interface()
456 {
457 	SCSI_HBA_LOG((_LOG(TRACE, NC), NULL, NULL,
458 	    "scsi_initialize_hba_interface"));
459 
460 	mutex_init(&scsi_log_mutex, NULL, MUTEX_DRIVER, NULL);
461 	mutex_init(&scsi_flag_nointr_mutex, NULL, MUTEX_DRIVER, NULL);
462 	cv_init(&scsi_flag_nointr_cv, NULL, CV_DRIVER, NULL);
463 	mutex_init(&scsi_hba_log_mutex, NULL, MUTEX_DRIVER, NULL);
464 }
465 
466 int
467 scsi_hba_pkt_constructor(void *buf, void *arg, int kmflag)
468 {
469 	struct scsi_pkt_cache_wrapper *pktw;
470 	struct scsi_pkt		*pkt;
471 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
472 	int			pkt_len;
473 	char			*ptr;
474 
475 	/*
476 	 * allocate a chunk of memory for the following:
477 	 * scsi_pkt
478 	 * pcw_* fields
479 	 * pkt_ha_private
480 	 * pkt_cdbp, if needed
481 	 * (pkt_private always null)
482 	 * pkt_scbp, if needed
483 	 */
484 	pkt_len = tran->tran_hba_len + sizeof (struct scsi_pkt_cache_wrapper);
485 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB)
486 		pkt_len += DEFAULT_CDBLEN;
487 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
488 		pkt_len += DEFAULT_SCBLEN;
489 	bzero(buf, pkt_len);
490 
491 	ptr = buf;
492 	pktw = buf;
493 	ptr += sizeof (struct scsi_pkt_cache_wrapper);
494 	pkt = &(pktw->pcw_pkt);
495 	pkt->pkt_ha_private = (opaque_t)ptr;
496 
497 	pktw->pcw_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
498 	/*
499 	 * keep track of the granularity at the time this handle was
500 	 * allocated
501 	 */
502 	pktw->pcw_granular = tran->tran_dma_attr.dma_attr_granular;
503 
504 	if (ddi_dma_alloc_handle(tran->tran_hba_dip,
505 	    &tran->tran_dma_attr,
506 	    kmflag == KM_SLEEP ? SLEEP_FUNC: NULL_FUNC, NULL,
507 	    &pkt->pkt_handle) != DDI_SUCCESS) {
508 
509 		return (-1);
510 	}
511 	ptr += tran->tran_hba_len;
512 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) {
513 		pkt->pkt_cdbp = (opaque_t)ptr;
514 		ptr += DEFAULT_CDBLEN;
515 	}
516 	pkt->pkt_private = NULL;
517 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
518 		pkt->pkt_scbp = (opaque_t)ptr;
519 	if (tran->tran_pkt_constructor)
520 		return ((*tran->tran_pkt_constructor)(pkt, arg, kmflag));
521 	else
522 		return (0);
523 }
524 
525 #define	P_TO_TRAN(pkt)	((pkt)->pkt_address.a_hba_tran)
526 
527 void
528 scsi_hba_pkt_destructor(void *buf, void *arg)
529 {
530 	struct scsi_pkt_cache_wrapper *pktw = buf;
531 	struct scsi_pkt		*pkt = &(pktw->pcw_pkt);
532 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
533 
534 	ASSERT(pktw->pcw_magic == PKT_WRAPPER_MAGIC);
535 	ASSERT((pktw->pcw_flags & PCW_BOUND) == 0);
536 	if (tran->tran_pkt_destructor)
537 		(*tran->tran_pkt_destructor)(pkt, arg);
538 
539 	/* make sure nobody messed with our pointers */
540 	ASSERT(pkt->pkt_ha_private == (opaque_t)((char *)pkt +
541 	    sizeof (struct scsi_pkt_cache_wrapper)));
542 	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_SCB) == 0) ||
543 	    (pkt->pkt_scbp == (opaque_t)((char *)pkt +
544 	    tran->tran_hba_len +
545 	    (((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ?
546 	    0 : DEFAULT_CDBLEN) +
547 	    DEFAULT_PRIVLEN + sizeof (struct scsi_pkt_cache_wrapper))));
548 	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ||
549 	    (pkt->pkt_cdbp == (opaque_t)((char *)pkt +
550 	    tran->tran_hba_len +
551 	    sizeof (struct scsi_pkt_cache_wrapper))));
552 	ASSERT(pkt->pkt_handle);
553 	ddi_dma_free_handle(&pkt->pkt_handle);
554 	pkt->pkt_handle = NULL;
555 	pkt->pkt_numcookies = 0;
556 	pktw->pcw_total_xfer = 0;
557 	pktw->pcw_totalwin = 0;
558 	pktw->pcw_curwin = 0;
559 }
560 
561 /*
562  * Called by an HBA from _init() to plumb in common SCSA bus_ops and
563  * cb_ops for the HBA's :devctl and :scsi minor nodes.
564  */
565 int
566 scsi_hba_init(struct modlinkage *modlp)
567 {
568 	struct dev_ops *hba_dev_ops;
569 
570 	SCSI_HBA_LOG((_LOG(TRACE, NC), NULL, NULL, "scsi_hba_init"));
571 
572 	/*
573 	 * Get a pointer to the dev_ops structure of the HBA and plumb our
574 	 * bus_ops vector into the HBA's dev_ops structure.
575 	 */
576 	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
577 	ASSERT(hba_dev_ops->devo_bus_ops == NULL);
578 	hba_dev_ops->devo_bus_ops = &scsi_hba_busops;
579 
580 	/*
581 	 * Plumb our cb_ops vector into the HBA's dev_ops structure to
582 	 * provide getinfo and hotplugging ioctl support if the HBA driver
583 	 * does not already provide this support.
584 	 */
585 	if (hba_dev_ops->devo_cb_ops == NULL) {
586 		hba_dev_ops->devo_cb_ops = &scsi_hba_cbops;
587 	}
588 	if (hba_dev_ops->devo_cb_ops->cb_open == scsi_hba_open) {
589 		ASSERT(hba_dev_ops->devo_cb_ops->cb_close == scsi_hba_close);
590 		hba_dev_ops->devo_getinfo = scsi_hba_info;
591 	}
592 	return (0);
593 }
594 
595 /*
596  * Called by an HBA attach(9E) to allocate a scsi_hba_tran structure. An HBA
597  * driver will then initialize the structure and then call
598  * scsi_hba_attach_setup.
599  */
600 /*ARGSUSED*/
601 scsi_hba_tran_t *
602 scsi_hba_tran_alloc(
603 	dev_info_t		*self,
604 	int			flags)
605 {
606 	scsi_hba_tran_t		*tran;
607 
608 	SCSI_HBA_LOG((_LOG(TRACE, NC), self, NULL, "scsi_hba_tran_alloc"));
609 
610 	tran = kmem_zalloc(sizeof (scsi_hba_tran_t),
611 	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
612 
613 	if (tran) {
614 		tran->tran_interconnect_type = INTERCONNECT_PARALLEL;
615 		tran->tran_hba_flags |= SCSI_HBA_TRAN_ALLOC;
616 	}
617 
618 	return (tran);
619 }
620 
621 /*
622  * Called by an HBA to free a scsi_hba_tran structure
623  */
624 void
625 scsi_hba_tran_free(
626 	scsi_hba_tran_t		*tran)
627 {
628 	SCSI_HBA_LOG((_LOG(TRACE, NC), NULL, NULL, "scsi_hba_tran_free"));
629 
630 	kmem_free(tran, sizeof (scsi_hba_tran_t));
631 }
632 
633 int
634 scsi_tran_ext_alloc(
635 	scsi_hba_tran_t		*tran,
636 	size_t			length,
637 	int			flags)
638 {
639 	void	*tran_ext;
640 	int	ret = DDI_FAILURE;
641 
642 	tran_ext = kmem_zalloc(length,
643 	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
644 	if (tran_ext != NULL) {
645 		tran->tran_extension = tran_ext;
646 		ret = DDI_SUCCESS;
647 	}
648 	return (ret);
649 }
650 
651 void
652 scsi_tran_ext_free(
653 	scsi_hba_tran_t		*tran,
654 	size_t			length)
655 {
656 	if (tran->tran_extension != NULL) {
657 		kmem_free(tran->tran_extension, length);
658 		tran->tran_extension = NULL;
659 	}
660 }
661 
662 /*
663  * Obsolete: Called by an HBA to attach an instance of the driver
664  * Implement this older interface in terms of the new.
665  */
666 /*ARGSUSED*/
667 int
668 scsi_hba_attach(
669 	dev_info_t		*self,
670 	ddi_dma_lim_t		*hba_lim,
671 	scsi_hba_tran_t		*tran,
672 	int			flags,
673 	void			*hba_options)
674 {
675 	ddi_dma_attr_t		hba_dma_attr;
676 
677 	bzero(&hba_dma_attr, sizeof (ddi_dma_attr_t));
678 
679 	hba_dma_attr.dma_attr_burstsizes = hba_lim->dlim_burstsizes;
680 	hba_dma_attr.dma_attr_minxfer = hba_lim->dlim_minxfer;
681 
682 	return (scsi_hba_attach_setup(self, &hba_dma_attr, tran, flags));
683 }
684 
685 /*
686  * Called by an HBA to attach an instance of the driver.
687  */
688 int
689 scsi_hba_attach_setup(
690 	dev_info_t		*self,
691 	ddi_dma_attr_t		*hba_dma_attr,
692 	scsi_hba_tran_t		*tran,
693 	int			flags)
694 {
695 	struct dev_ops		*hba_dev_ops;
696 	int			id;
697 	int			capable;
698 	static const char	*interconnect[] = INTERCONNECT_TYPE_ASCII;
699 
700 	SCSI_HBA_LOG((_LOG(TRACE, NC), self, NULL, "scsi_hba_attach_setup"));
701 
702 	/*
703 	 * Verify correct scsi_hba_tran_t form:
704 	 *   o	both or none of tran_get_name/tran_get_addr.
705 	 */
706 	if ((tran->tran_get_name == NULL) ^
707 	    (tran->tran_get_bus_addr == NULL)) {
708 		SCSI_HBA_LOG((_LOG(WARN, ATTACH_SETUP), self, NULL,
709 		    "should support both or neither: "
710 		    "tran_get_name, tran_get_bus_addr"));
711 		return (DDI_FAILURE);
712 	}
713 
714 	/*
715 	 * Save all the important HBA information that must be accessed
716 	 * later by scsi_hba_bus_ctl(), and scsi_hba_map().
717 	 */
718 	tran->tran_hba_dip = self;
719 	tran->tran_hba_flags &= SCSI_HBA_TRAN_ALLOC;
720 	tran->tran_hba_flags |= (flags & ~SCSI_HBA_TRAN_ALLOC);
721 
722 	/*
723 	 * Note: we only need dma_attr_minxfer and dma_attr_burstsizes
724 	 * from the DMA attributes. scsi_hba_attach(9f) only
725 	 * guarantees that these two fields are initialized properly.
726 	 * If this changes, be sure to revisit the implementation
727 	 * of scsi_hba_attach(9F).
728 	 */
729 	(void) memcpy(&tran->tran_dma_attr, hba_dma_attr,
730 	    sizeof (ddi_dma_attr_t));
731 
732 	/* create kmem_cache, if needed */
733 	if (tran->tran_setup_pkt) {
734 		char tmp[96];
735 		int hbalen;
736 		int cmdlen = 0;
737 		int statuslen = 0;
738 
739 		ASSERT(tran->tran_init_pkt == NULL);
740 		ASSERT(tran->tran_destroy_pkt == NULL);
741 
742 		tran->tran_init_pkt = scsi_init_cache_pkt;
743 		tran->tran_destroy_pkt = scsi_free_cache_pkt;
744 		tran->tran_sync_pkt = scsi_sync_cache_pkt;
745 		tran->tran_dmafree = scsi_cache_dmafree;
746 
747 		hbalen = ROUNDUP(tran->tran_hba_len);
748 		if (flags & SCSI_HBA_TRAN_CDB)
749 			cmdlen = ROUNDUP(DEFAULT_CDBLEN);
750 		if (flags & SCSI_HBA_TRAN_SCB)
751 			statuslen = ROUNDUP(DEFAULT_SCBLEN);
752 
753 		(void) snprintf(tmp, sizeof (tmp), "pkt_cache_%s_%d",
754 		    ddi_driver_name(self), ddi_get_instance(self));
755 		tran->tran_pkt_cache_ptr = kmem_cache_create(tmp,
756 		    sizeof (struct scsi_pkt_cache_wrapper) +
757 		    hbalen + cmdlen + statuslen, 8,
758 		    scsi_hba_pkt_constructor, scsi_hba_pkt_destructor,
759 		    NULL, tran, NULL, 0);
760 	}
761 
762 	/*
763 	 * If the property does not already exist on self then see if we can
764 	 * pull it from further up the tree and define it on self. If the
765 	 * property does not exist above (including options.conf) then use the
766 	 * default value specified (global variable).
767 	 */
768 #define	CONFIG_INT_PROP(s, p, dv)	{				\
769 	if ((ddi_prop_exists(DDI_DEV_T_ANY, s,				\
770 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, p) == 0) &&		\
771 	    (ndi_prop_update_int(DDI_DEV_T_NONE, s, p,			\
772 	    ddi_prop_get_int(DDI_DEV_T_ANY, ddi_get_parent(s),		\
773 	    DDI_PROP_NOTPROM, p, dv)) != DDI_PROP_SUCCESS))		\
774 		SCSI_HBA_LOG((_LOG(WARN, ATTACH_SETUP), NULL, s,	\
775 		    "cannot create property '%s'", p));			\
776 	}
777 
778 	/*
779 	 * Attach scsi configuration property parameters not already defined
780 	 * via driver.conf to this instance of the HBA using global variable
781 	 * value.  Pulling things down from above us to use
782 	 * "DDI_PROP_NOTPROM | DDI_PROP_DONTPASS" for faster access.
783 	 */
784 	CONFIG_INT_PROP(self, "scsi-options", scsi_options);
785 	CONFIG_INT_PROP(self, "scsi-reset-delay", scsi_reset_delay);
786 	CONFIG_INT_PROP(self, "scsi-tag-age-limit", scsi_tag_age_limit);
787 	CONFIG_INT_PROP(self, "scsi-watchdog-tick", scsi_watchdog_tick);
788 	CONFIG_INT_PROP(self, "scsi-selection-timeout", scsi_selection_timeout);
789 
790 	/*
791 	 * cache the scsi-initiator-id as a property defined further up
792 	 * the tree or defined by OBP on the HBA node so can use
793 	 * "DDI_PROP_NOTPROM | DDI_PROP_DONTPASS" during enumeration.
794 	 * We perform the same type of operation that an HBA driver would
795 	 * use to obtain the 'initiator-id' capability.
796 	 */
797 	id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0, "initiator-id", -1);
798 	if (id == -1)
799 		id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0,
800 		    "scsi-initiator-id", -1);
801 	if (id != -1)
802 		CONFIG_INT_PROP(self, "scsi-initiator-id", id);
803 
804 	/* Establish 'initiator-interconnect-type' */
805 	if ((tran->tran_hba_flags & SCSI_HBA_TRAN_ALLOC) &&
806 	    (tran->tran_interconnect_type > 0) &&
807 	    (tran->tran_interconnect_type < INTERCONNECT_MAX)) {
808 		if (ndi_prop_update_string(DDI_DEV_T_NONE, self,
809 		    "initiator-interconnect-type",
810 		    (char *)interconnect[tran->tran_interconnect_type])
811 		    != DDI_PROP_SUCCESS) {
812 			SCSI_HBA_LOG((_LOG(WARN, ATTACH_SETUP), NULL, self,
813 			    "failed to establish "
814 			    "'initiator-interconnect-type'"));
815 			return (DDI_FAILURE);
816 		}
817 	}
818 
819 	/* SCSA iport driver_private (devi_driver_data) points to tran */
820 	ddi_set_driver_private(self, tran);
821 
822 	/*
823 	 * Create :devctl and :scsi minor nodes unless driver supplied its own
824 	 * open/close entry points
825 	 */
826 	hba_dev_ops = ddi_get_driver(self);
827 	ASSERT(hba_dev_ops != NULL);
828 	if (hba_dev_ops == NULL)
829 		return (DDI_FAILURE);
830 	if (hba_dev_ops->devo_cb_ops->cb_open == scsi_hba_open) {
831 		/*
832 		 * Make sure that instance number doesn't overflow
833 		 * when forming minor numbers.
834 		 */
835 		ASSERT(ddi_get_instance(self) <=
836 		    (L_MAXMIN >> INST_MINOR_SHIFT));
837 
838 		if ((ddi_create_minor_node(self, "devctl", S_IFCHR,
839 		    INST2DEVCTL(ddi_get_instance(self)),
840 		    DDI_NT_SCSI_NEXUS, 0) != DDI_SUCCESS) ||
841 		    (ddi_create_minor_node(self, "scsi", S_IFCHR,
842 		    INST2SCSI(ddi_get_instance(self)),
843 		    DDI_NT_SCSI_ATTACHMENT_POINT, 0) != DDI_SUCCESS)) {
844 			ddi_remove_minor_node(self, "devctl");
845 			ddi_remove_minor_node(self, "scsi");
846 			SCSI_HBA_LOG((_LOG(WARN, ATTACH_SETUP), self, NULL,
847 			    "cannot create devctl/scsi minor nodes"));
848 		}
849 	}
850 
851 	/*
852 	 * NOTE: SCSA maintains an 'fm-capable' domain, in tran_fm_capable,
853 	 * that is not dependent (limited by) the capabilities of its parents.
854 	 * For example a dip in a branch that is not DDI_FM_EREPORT_CAPABLE
855 	 * may report as capable, via tran_fm_capable, to its scsi_device
856 	 * children.
857 	 *
858 	 * Get 'fm-capable' property from driver.conf, if present. If not
859 	 * present, default to the scsi_fm_capable global (which has
860 	 * DDI_FM_EREPORT_CAPABLE set by default).
861 	 */
862 	if (tran->tran_fm_capable == DDI_FM_NOT_CAPABLE)
863 		tran->tran_fm_capable = ddi_prop_get_int(DDI_DEV_T_ANY, self,
864 		    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
865 		    "fm-capable", scsi_fm_capable);
866 
867 	/*
868 	 * If an HBA is *not* doing its own fma support by calling
869 	 * ddi_fm_init() prior to scsi_hba_attach_setup(), we provide a
870 	 * minimal common SCSA implementation so that scsi_device children
871 	 * can generate ereports via scsi_fm_ereport_post().  We use
872 	 * ddi_fm_capable() to detect an HBA calling ddi_fm_init() prior to
873 	 * scsi_hba_attach_setup().
874 	 */
875 	if (tran->tran_fm_capable &&
876 	    (ddi_fm_capable(self) == DDI_FM_NOT_CAPABLE)) {
877 		/*
878 		 * We are capable of something, pass our capabilities up
879 		 * the tree, but use a local variable so our parent can't
880 		 * limit our capabilities (we don't want our parent to
881 		 * clear DDI_FM_EREPORT_CAPABLE).
882 		 *
883 		 * NOTE: iblock cookies are not important because scsi
884 		 * HBAs always interrupt below LOCK_LEVEL.
885 		 */
886 		capable = tran->tran_fm_capable;
887 		ddi_fm_init(self, &capable, NULL);
888 
889 		/*
890 		 * Set SCSI_HBA_TRAN_FMSCSA bit to mark us as usiung the
891 		 * common minimal SCSA fm implementation -  we called
892 		 * ddi_fm_init(), so we are responsible for calling
893 		 * ddi_fm_fini() in scsi_hba_detach().
894 		 * NOTE: if ddi_fm_init fails in any reason, SKIP.
895 		 */
896 		if (DEVI(self)->devi_fmhdl)
897 			tran->tran_hba_flags |= SCSI_HBA_TRAN_FMSCSA;
898 	}
899 
900 	return (DDI_SUCCESS);
901 }
902 
903 /*
904  * Called by an HBA to detach an instance of the driver
905  */
906 int
907 scsi_hba_detach(dev_info_t *self)
908 {
909 	struct dev_ops		*hba_dev_ops;
910 	scsi_hba_tran_t		*tran;
911 
912 	SCSI_HBA_LOG((_LOG(TRACE, NC), self, NULL, "scsi_hba_detach"));
913 
914 	tran = ddi_get_driver_private(self);
915 	ASSERT(tran);
916 	if (tran == NULL)
917 		return (DDI_FAILURE);
918 	ASSERT(tran->tran_open_flag == 0);
919 	if (tran->tran_open_flag)
920 		return (DDI_FAILURE);
921 
922 	ddi_set_driver_private(self, NULL);
923 
924 	/*
925 	 * If we are taking care of mininal default fma implementation,
926 	 * call ddi_fm_fini(9F).
927 	 */
928 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_FMSCSA) {
929 		ddi_fm_fini(self);
930 	}
931 
932 	hba_dev_ops = ddi_get_driver(self);
933 	ASSERT(hba_dev_ops != NULL);
934 	if (hba_dev_ops == NULL)
935 		return (DDI_FAILURE);
936 	if (hba_dev_ops->devo_cb_ops->cb_open == scsi_hba_open) {
937 		ddi_remove_minor_node(self, "devctl");
938 		ddi_remove_minor_node(self, "scsi");
939 	}
940 
941 
942 	/*
943 	 * XXX - scsi_transport.h states that these data fields should not be
944 	 * referenced by the HBA. However, to be consistent with
945 	 * scsi_hba_attach(), they are being reset.
946 	 */
947 	tran->tran_hba_dip = (dev_info_t *)NULL;
948 	tran->tran_hba_flags = 0;
949 	(void) memset(&tran->tran_dma_attr, 0, sizeof (ddi_dma_attr_t));
950 
951 	if (tran->tran_pkt_cache_ptr != NULL) {
952 		kmem_cache_destroy(tran->tran_pkt_cache_ptr);
953 		tran->tran_pkt_cache_ptr = NULL;
954 	}
955 
956 	return (DDI_SUCCESS);
957 }
958 
959 /*
960  * Called by an HBA from _fini()
961  */
962 void
963 scsi_hba_fini(struct modlinkage *modlp)
964 {
965 	struct dev_ops *hba_dev_ops;
966 
967 	SCSI_HBA_LOG((_LOG(TRACE, NC), NULL, NULL, "scsi_hba_fini"));
968 
969 	/* Get the devops structure of this module and clear bus_ops vector. */
970 	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
971 
972 	if (hba_dev_ops->devo_cb_ops == &scsi_hba_cbops)
973 		hba_dev_ops->devo_cb_ops = NULL;
974 
975 	if (hba_dev_ops->devo_getinfo == scsi_hba_info)
976 		hba_dev_ops->devo_getinfo = NULL;
977 
978 	hba_dev_ops->devo_bus_ops = (struct bus_ops *)NULL;
979 }
980 
981 static int
982 smp_busctl_reportdev(dev_info_t *child)
983 {
984 	dev_info_t		*self = ddi_get_parent(child);
985 	char			*smp_wwn;
986 
987 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
988 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
989 	    SMP_WWN, &smp_wwn) != DDI_SUCCESS) {
990 		return (DDI_FAILURE);
991 	}
992 	cmn_err(CE_CONT,
993 	    "?%s%d at %s%d: wwn %s\n",
994 	    ddi_driver_name(child), ddi_get_instance(child),
995 	    ddi_driver_name(self), ddi_get_instance(self),
996 	    smp_wwn);
997 	ddi_prop_free(smp_wwn);
998 	return (DDI_SUCCESS);
999 }
1000 
1001 static int
1002 smp_busctl_initchild(dev_info_t *child)
1003 {
1004 	dev_info_t		*self = ddi_get_parent(child);
1005 	scsi_hba_tran_t		*tran = ddi_get_driver_private(self);
1006 	struct smp_device	*smp;
1007 	char			addr[SCSI_MAXNAMELEN];
1008 	dev_info_t		*ndip;
1009 	char			*smp_wwn;
1010 	uint64_t		wwn;
1011 
1012 	ASSERT(tran);
1013 	if (tran == NULL)
1014 		return (DDI_FAILURE);
1015 
1016 	/*
1017 	 * Clone transport structure if requested, so the HBA can maintain
1018 	 * target-specific info, if necessary.
1019 	 *
1020 	 * NOTE: when mpt is converted to SCSI_HBA_ADDR_COMPLEX (and
1021 	 * smp_hba_private is added to struct smp_device) then
1022 	 * smp support of SCSI_HBA_TRAN_CLONE can be removed (i.e.
1023 	 * we can ASSERT that drivers with smp children must be
1024 	 * SCSI_HBA_ADDR_COMPLEX).
1025 	 */
1026 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1027 		scsi_hba_tran_t	*clone =
1028 		    kmem_alloc(sizeof (scsi_hba_tran_t), KM_SLEEP);
1029 
1030 		bcopy(tran, clone, sizeof (scsi_hba_tran_t));
1031 		tran = clone;
1032 	}
1033 
1034 	smp = kmem_zalloc(sizeof (struct smp_device), KM_SLEEP);
1035 	smp->dip = child;
1036 	smp->smp_addr.a_hba_tran = tran;
1037 
1038 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1039 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1040 	    SMP_WWN, &smp_wwn) != DDI_SUCCESS) {
1041 		return (DDI_FAILURE);
1042 	}
1043 
1044 	if (ddi_devid_str_to_wwn(smp_wwn, &wwn)) {
1045 		goto failure;
1046 	}
1047 
1048 	bcopy(&wwn, smp->smp_addr.a_wwn, SAS_WWN_BYTE_SIZE);
1049 	(void) snprintf(addr, SCSI_MAXNAMELEN, "w%s", smp_wwn);
1050 
1051 	/* Prevent duplicate nodes.  */
1052 	ndip = ndi_devi_find(self, ddi_node_name(child), addr);
1053 	if (ndip && (ndip != child)) {
1054 		goto failure;
1055 	}
1056 
1057 	ddi_set_name_addr(child, addr);
1058 	ddi_set_driver_private(child, smp);
1059 	ddi_prop_free(smp_wwn);
1060 	return (DDI_SUCCESS);
1061 
1062 failure:
1063 	kmem_free(smp, sizeof (struct smp_device));
1064 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1065 		kmem_free(tran, sizeof (scsi_hba_tran_t));
1066 	}
1067 	ddi_prop_free(smp_wwn);
1068 	return (DDI_FAILURE);
1069 }
1070 
1071 static int
1072 smp_busctl_uninitchild(dev_info_t *child)
1073 {
1074 	dev_info_t		*self = ddi_get_parent(child);
1075 	struct smp_device	*smp = ddi_get_driver_private(child);
1076 	scsi_hba_tran_t		*tran = ddi_get_driver_private(self);
1077 
1078 	ASSERT(smp && tran);
1079 	if ((smp == NULL) || (tran == NULL))
1080 		return (DDI_FAILURE);
1081 
1082 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1083 		tran = smp->smp_addr.a_hba_tran;
1084 		kmem_free(tran, sizeof (scsi_hba_tran_t));
1085 	}
1086 	kmem_free(smp, sizeof (*smp));
1087 
1088 	ddi_set_driver_private(child, NULL);
1089 	ddi_set_name_addr(child, NULL);
1090 	return (DDI_SUCCESS);
1091 }
1092 
1093 /*
1094  * Wrapper to scsi_get_name which takes a devinfo argument instead of a
1095  * scsi_device structure.
1096  */
1097 static int
1098 scsi_hba_name_child(dev_info_t *child, char *addr, int maxlen)
1099 {
1100 	struct scsi_device	*sd = ddi_get_driver_private(child);
1101 
1102 	/* nodes are named by tran_get_name or default "tgt,lun" */
1103 	if (sd && (scsi_get_name(sd, addr, maxlen) == 1))
1104 		return (DDI_SUCCESS);
1105 
1106 	return (DDI_FAILURE);
1107 }
1108 
1109 static int
1110 scsi_busctl_reportdev(dev_info_t *child)
1111 {
1112 	dev_info_t		*self = ddi_get_parent(child);
1113 	scsi_hba_tran_t		*tran = ddi_get_driver_private(self);
1114 	struct scsi_device	*sd = ddi_get_driver_private(child);
1115 	char			ua[SCSI_MAXNAMELEN];
1116 	char			ba[SCSI_MAXNAMELEN];
1117 
1118 	SCSI_HBA_LOG((_LOG(TRACE, BUS_CTL), NULL, child,
1119 	    "scsi_hba_bus_ctl REPORTDEV"));
1120 
1121 	ASSERT(tran && sd);
1122 	if ((tran == NULL) || (sd == NULL))
1123 		return (DDI_FAILURE);
1124 
1125 	/* get the unit_address and bus_addr information */
1126 	if ((scsi_get_name(sd, ua, sizeof (ua)) == 0) ||
1127 	    (scsi_get_bus_addr(sd, ba, sizeof (ba)) == 0)) {
1128 		SCSI_HBA_LOG((_LOG(DIAG1, BUS_CTL),
1129 		    NULL, child, "REPORTDEV failure"));
1130 		return (DDI_FAILURE);
1131 	}
1132 
1133 	if (tran->tran_get_name == NULL)
1134 		SCSI_HBA_LOG((_LOG(CONT, NC), NULL, NULL,
1135 		    "?%s%d at %s%d: %s",
1136 		    ddi_driver_name(child), ddi_get_instance(child),
1137 		    ddi_driver_name(self), ddi_get_instance(self), ba));
1138 	else
1139 		SCSI_HBA_LOG((_LOG(CONT, NC), NULL, NULL,
1140 		    "?%s%d at %s%d: name %s, bus address %s",
1141 		    ddi_driver_name(child), ddi_get_instance(child),
1142 		    ddi_driver_name(self), ddi_get_instance(self),
1143 		    ua, ba));
1144 	return (DDI_SUCCESS);
1145 }
1146 
1147 /*
1148  * scsi_busctl_initchild is called to initialize the SCSA transport for
1149  * communication with a particular child scsi target device. Successful
1150  * initialization requires properties on the node which describe the address
1151  * of the target device. If the address of the target device can't be
1152  * determined from properties then DDI_NOT_WELL_FORMED is returned. Nodes that
1153  * are DDI_NOT_WELL_FORMED are considered an implementation artifact.
1154  * The child may be one of the following types of devinfo nodes:
1155  *
1156  * OBP node:
1157  *	OBP does not enumerate target devices attached a SCSI bus. These
1158  *	template/stub/wildcard nodes are a legacy artifact for support of old
1159  *	driver loading methods. Since they have no properties,
1160  *	DDI_NOT_WELL_FORMED will be returned.
1161  *
1162  * SID node:
1163  *	The node may be either a:
1164  *	    o	probe/barrier SID node
1165  *	    o	a dynamic SID target node
1166  *	    o	a dynamic SID mscsi node
1167  *
1168  * driver.conf node: The situation for this nexus is different than most.
1169  *	Typically a driver.conf node definition is used to either define a
1170  *	new child devinfo node or to further decorate (via merge) a SID
1171  *	child with properties. In our case we use the nodes for *both*
1172  *	purposes.
1173  *
1174  * In both the SID node and driver.conf node cases we must form the nodes
1175  * "@addr" from the well-known scsi(9P) device unit-address properties on
1176  * the node.
1177  *
1178  * For HBA drivers that implement the deprecated tran_get_name interface,
1179  * "@addr" construction involves having that driver interpret properties via
1180  * scsi_hba_name_child -> scsi_get_name -> tran_get_name: there is no
1181  * requiremnt for the property names to be well-known.
1182  */
1183 static int
1184 scsi_busctl_initchild(dev_info_t *child)
1185 {
1186 	dev_info_t		*self = ddi_get_parent(child);
1187 	dev_info_t		*dup;
1188 	scsi_hba_tran_t		*tran;
1189 	struct scsi_device	*sd;
1190 	scsi_hba_tran_t		*tran_clone;
1191 	int			tgt = 0;
1192 	int			lun = 0;
1193 	int			sfunc = 0;
1194 	int			err = DDI_FAILURE;
1195 	char			addr[SCSI_MAXNAMELEN];
1196 
1197 	ASSERT(DEVI_BUSY_OWNED(self));
1198 	SCSI_HBA_LOG((_LOG(DIAG4, DEVICE_INITCHILD),
1199 	    NULL, child, "begin initchild"));
1200 
1201 	/*
1202 	 * For a driver like fp with multiple upper-layer-protocols
1203 	 * it is possible for scsi_hba_init in _init to plumb SCSA
1204 	 * and have the load of fcp (which does scsi_hba_attach_setup)
1205 	 * to fail.  In this case we may get here with a NULL hba.
1206 	 */
1207 	tran = ddi_get_driver_private(self);
1208 	if (tran == NULL)
1209 		return (DDI_NOT_WELL_FORMED);
1210 
1211 	/*
1212 	 * OBP may create template/stub/wildcard nodes for legacy driver
1213 	 * loading methods. These nodes have no properties, so we lack the
1214 	 * addressing properties to initchild them. Hide the node and return
1215 	 * DDI_NOT_WELL_FORMED.
1216 	 *
1217 	 * XXX need ndi_devi_has_properties(dip) type interface?
1218 	 *
1219 	 * XXX It would be nice if we could delete these ill formed nodes by
1220 	 * implementing a DDI_NOT_WELL_FORMED_DELETE return code. This can't
1221 	 * be done until leadville debug code removes its dependencies
1222 	 * on the devinfo still being present after a failed ndi_devi_online.
1223 	 */
1224 	if ((DEVI(child)->devi_hw_prop_ptr == NULL) &&
1225 	    (DEVI(child)->devi_drv_prop_ptr == NULL) &&
1226 	    (DEVI(child)->devi_sys_prop_ptr == NULL)) {
1227 		SCSI_HBA_LOG((_LOG(DIAG4, DEVICE_INITCHILD),
1228 		    NULL, child, "no properties"));
1229 		return (DDI_NOT_WELL_FORMED);
1230 	}
1231 
1232 	/* get legacy SPI addressing properties */
1233 	sfunc = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1234 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, SCSI_ADDR_PROP_SFUNC, -1);
1235 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1236 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
1237 	if ((tgt = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1238 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
1239 	    SCSI_ADDR_PROP_TARGET, -1)) == -1) {
1240 		tgt = 0;
1241 		/*
1242 		 * A driver.conf node for merging always has a target= property,
1243 		 * even if it is just a dummy that does not contain the real
1244 		 * target address. However drivers that register devids may
1245 		 * create stub driver.conf nodes without a target= property so
1246 		 * that pathological devid resolution works.
1247 		 */
1248 		if (ndi_dev_is_persistent_node(child) == 0) {
1249 			SCSI_HBA_LOG((_LOG(DIAG4, DEVICE_INITCHILD),
1250 			    NULL, child, "stub driver.conf node"));
1251 			return (DDI_NOT_WELL_FORMED);
1252 		}
1253 	}
1254 
1255 	/*
1256 	 * The scsi_address structure may not specify all the addressing
1257 	 * information. For an old HBA that doesn't support tran_get_name
1258 	 * (most pre-SCSI-3 HBAs) the scsi_address structure is still used,
1259 	 * so the target property must exist and the LUN must be < 256.
1260 	 */
1261 	if ((tran->tran_get_name == NULL) &&
1262 	    ((tgt >= USHRT_MAX) || (lun >= 256))) {
1263 		SCSI_HBA_LOG((_LOG(DIAG1, DEVICE_INITCHILD),
1264 		    NULL, child, "illegal or missing addressing properties"));
1265 		return (DDI_NOT_WELL_FORMED);
1266 	}
1267 
1268 	/*
1269 	 * We need to initialize a fair amount of our environment to invoke
1270 	 * tran_get_name (via scsi_hba_name_child and scsi_get_name) to
1271 	 * produce the "@addr" name from addressing properties. Allocate and
1272 	 * initialize scsi device structure.
1273 	 */
1274 	sd = kmem_zalloc(sizeof (struct scsi_device), KM_SLEEP);
1275 	mutex_init(&sd->sd_mutex, NULL, MUTEX_DRIVER, NULL);
1276 	sd->sd_dev = child;
1277 	sd->sd_pathinfo = NULL;
1278 	ddi_set_driver_private(child, sd);
1279 
1280 	if (tran->tran_hba_flags & SCSI_HBA_ADDR_COMPLEX) {
1281 		/*
1282 		 * For a SCSI_HBA_ADDR_COMPLEX transport we store a pointer to
1283 		 * scsi_device in the scsi_address structure.  This allows an
1284 		 * HBA driver to find its per-scsi_device private data
1285 		 * (accessable to the HBA given just the scsi_address by using
1286 		 *  scsi_address_device(9F)/scsi_device_hba_private_get(9F)).
1287 		 */
1288 		sd->sd_address.a.a_sd = sd;
1289 		tran_clone = NULL;
1290 	} else {
1291 		/*
1292 		 * Initialize the scsi_address so that a SCSI-2 target driver
1293 		 * talking to a SCSI-2 device on a SCSI-3 bus (spi) continues
1294 		 * to work. We skew the secondary function value so that we
1295 		 * can tell from the address structure if we are processing
1296 		 * a secondary function request.
1297 		 */
1298 		sd->sd_address.a_target = (ushort_t)tgt;
1299 		sd->sd_address.a_lun = (uchar_t)lun;
1300 		if (sfunc == -1)
1301 			sd->sd_address.a_sublun = (uchar_t)0;
1302 		else
1303 			sd->sd_address.a_sublun = (uchar_t)sfunc + 1;
1304 
1305 		/*
1306 		 * XXX TODO: apply target/lun limitation logic for SPI
1307 		 * binding_set. If spi this is based on scsi_options WIDE
1308 		 * NLUNS some forms of lun limitation are based on the
1309 		 * device @lun 0
1310 		 */
1311 
1312 		/*
1313 		 * Deprecated: Use SCSI_HBA_ADDR_COMPLEX:
1314 		 *   Clone transport structure if requested. Cloning allows
1315 		 *   an HBA to maintain target-specific information if
1316 		 *   necessary, such as target addressing information that
1317 		 *   does not adhere to the scsi_address structure format.
1318 		 */
1319 		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1320 			tran_clone = kmem_alloc(
1321 			    sizeof (scsi_hba_tran_t), KM_SLEEP);
1322 			bcopy((caddr_t)tran,
1323 			    (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
1324 			tran = tran_clone;
1325 			tran->tran_sd = sd;
1326 		} else {
1327 			tran_clone = NULL;
1328 			ASSERT(tran->tran_sd == NULL);
1329 		}
1330 	}
1331 
1332 	/* establish scsi_address pointer to the HBA's tran structure */
1333 	sd->sd_address.a_hba_tran = tran;
1334 
1335 	/*
1336 	 * This is a grotty hack that allows direct-access (non-scsa) drivers
1337 	 * (like chs, ata, and mlx which all make cmdk children) to put its
1338 	 * own vector in the 'a_hba_tran' field. When all the drivers that do
1339 	 * this are fixed, please remove this hack.
1340 	 *
1341 	 * NOTE: This hack is also shows up in the DEVP_TO_TRAN implementation
1342 	 * in scsi_confsubr.c.
1343 	 */
1344 	sd->sd_tran_safe = tran;
1345 
1346 	/* Establish the @addr name of the child. */
1347 	*addr = '\0';
1348 	if (scsi_hba_name_child(child, addr, SCSI_MAXNAMELEN) != DDI_SUCCESS) {
1349 		/*
1350 		 * Some driver.conf files add bogus target properties (relative
1351 		 * to their nexus representation of target) to their stub
1352 		 * nodes, causing the check above to not filter them.
1353 		 */
1354 		SCSI_HBA_LOG((_LOG(DIAG3, DEVICE_INITCHILD),
1355 		    NULL, child, "failed name_child"));
1356 		err = DDI_NOT_WELL_FORMED;
1357 		goto failure;
1358 	}
1359 	if (*addr == '\0') {
1360 		SCSI_HBA_LOG((_LOG(DIAG2, DEVICE_INITCHILD),
1361 		    NULL, child, "failed to establish @addr"));
1362 		err = DDI_NOT_WELL_FORMED;
1363 		goto failure;
1364 	}
1365 
1366 	/* set the node @addr string */
1367 	ddi_set_name_addr(child, addr);
1368 
1369 	/* prevent sibling duplicates */
1370 	dup = ndi_devi_find(self, ddi_node_name(child), addr);
1371 	if (dup && (dup != child)) {
1372 		SCSI_HBA_LOG((_LOG(DIAG4, DEVICE_INITCHILD),
1373 		    NULL, child, "@%s duplicate %p", addr, (void *)dup));
1374 		goto failure;
1375 	}
1376 
1377 	/* call HBA's target init entry point if it exists */
1378 	if (tran->tran_tgt_init != NULL) {
1379 		if ((*tran->tran_tgt_init)
1380 		    (self, child, tran, sd) != DDI_SUCCESS) {
1381 			SCSI_HBA_LOG((_LOG(DIAG2, DEVICE_INITCHILD),
1382 			    NULL, child, "@%s failed tran_tgt_init", addr));
1383 			goto failure;
1384 		}
1385 	}
1386 
1387 	SCSI_HBA_LOG((_LOG(DIAG3, DEVICE_INITCHILD),
1388 	    NULL, child, "@%s ok", addr));
1389 	return (DDI_SUCCESS);
1390 
1391 failure:
1392 	if (tran_clone)
1393 		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
1394 	mutex_destroy(&sd->sd_mutex);
1395 	kmem_free(sd, sizeof (*sd));
1396 	ddi_set_driver_private(child, NULL);
1397 	ddi_set_name_addr(child, NULL);
1398 
1399 	return (err);		/* remove the node */
1400 }
1401 
1402 static int
1403 scsi_busctl_uninitchild(dev_info_t *child)
1404 {
1405 	dev_info_t		*self = ddi_get_parent(child);
1406 	scsi_hba_tran_t		*tran = ddi_get_driver_private(self);
1407 	struct scsi_device	*sd = ddi_get_driver_private(child);
1408 	scsi_hba_tran_t		*tran_clone;
1409 
1410 	ASSERT(DEVI_BUSY_OWNED(self));
1411 
1412 	ASSERT(tran && sd);
1413 	if ((tran == NULL) || (sd == NULL))
1414 		return (DDI_FAILURE);
1415 
1416 	SCSI_HBA_LOG((_LOG(DIAG3, DEVICE_UNINITCHILD),
1417 	    NULL, child, "uninitchild %d %s@%s", i_ddi_node_state(child),
1418 	    ddi_node_name(child),
1419 	    ddi_get_name_addr(child) ? ddi_get_name_addr(child) : "XXX"));
1420 
1421 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1422 		tran_clone = sd->sd_address.a_hba_tran;
1423 
1424 		/* ... grotty hack, involving sd_tran_safe, continued. */
1425 		if (tran_clone != sd->sd_tran_safe) {
1426 			tran_clone = sd->sd_tran_safe;
1427 #ifdef	DEBUG
1428 			/*
1429 			 * Complain so things get fixed and hack can, at
1430 			 * some point in time, be removed.
1431 			 */
1432 			cmn_err(CE_WARN, "scsi_busctl_uninitchild: '%s' is "
1433 			    "corrupting a_hba_tran",
1434 			    sd->sd_dev ? ddi_driver_name(sd->sd_dev) :
1435 			    "unknown_driver");
1436 #endif	/* DEBUG */
1437 		}
1438 
1439 		ASSERT(tran_clone->tran_hba_flags & SCSI_HBA_TRAN_CLONE);
1440 		ASSERT(tran_clone->tran_sd == sd);
1441 		tran = tran_clone;
1442 	} else {
1443 		tran_clone = NULL;
1444 		ASSERT(tran->tran_sd == NULL);
1445 	}
1446 
1447 	/*
1448 	 * To simplify host adapter drivers we guarantee that multiple
1449 	 * tran_tgt_init(9E) calls of the same unit address are never
1450 	 * active at the same time.
1451 	 */
1452 	if (tran->tran_tgt_free)
1453 		(*tran->tran_tgt_free) (self, child, tran, sd);
1454 
1455 	/*
1456 	 * If a inquiry data is still allocated (by scsi_probe()) we
1457 	 * free the allocation here. This keeps scsi_inq valid for the
1458 	 * same duration as the corresponding inquiry properties. It
1459 	 * also allows a tran_tgt_init() implementation that establishes
1460 	 * sd_inq (common/io/dktp/controller/ata/ata_disk.c) to deal
1461 	 * with deallocation in its tran_tgt_free (setting sd_inq back
1462 	 * to NULL) without upsetting the framework.
1463 	 */
1464 	if (sd->sd_inq) {
1465 		kmem_free(sd->sd_inq, SUN_INQSIZE);
1466 		sd->sd_inq = (struct scsi_inquiry *)NULL;
1467 	}
1468 
1469 	mutex_destroy(&sd->sd_mutex);
1470 	if (tran_clone)
1471 		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
1472 	kmem_free(sd, sizeof (*sd));
1473 
1474 	ddi_set_driver_private(child, NULL);
1475 	SCSI_HBA_LOG((_LOG(DIAG3, DEVICE_UNINITCHILD),
1476 	    NULL, child, "complete"));
1477 	ddi_set_name_addr(child, NULL);
1478 	return (DDI_SUCCESS);
1479 }
1480 
1481 /*
1482  * Generic bus_ctl operations for SCSI HBA's,
1483  * hiding the busctl interface from the HBA.
1484  */
1485 /*ARGSUSED*/
1486 static int
1487 scsi_hba_bus_ctl(
1488 	dev_info_t		*self,
1489 	dev_info_t		*child,
1490 	ddi_ctl_enum_t		op,
1491 	void			*arg,
1492 	void			*result)
1493 {
1494 	int			child_flavor_smp = 0;
1495 	int			val;
1496 	ddi_dma_attr_t		*attr;
1497 	scsi_hba_tran_t		*tran;
1498 
1499 	/* For some ops, child is 'arg'. */
1500 	if ((op == DDI_CTLOPS_INITCHILD) || (op == DDI_CTLOPS_UNINITCHILD))
1501 		child = (dev_info_t *)arg;
1502 
1503 	/* Determine the flavor of the child: smp .vs. scsi */
1504 	if (ddi_prop_exists(DDI_DEV_T_ANY, child,
1505 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, SMP_PROP))
1506 		child_flavor_smp = 1;
1507 
1508 	switch (op) {
1509 	case DDI_CTLOPS_INITCHILD:
1510 		if (child_flavor_smp)
1511 			return (smp_busctl_initchild(child));
1512 		else
1513 			return (scsi_busctl_initchild(child));
1514 
1515 	case DDI_CTLOPS_UNINITCHILD:
1516 		if (child_flavor_smp)
1517 			return (smp_busctl_uninitchild(child));
1518 		else
1519 			return (scsi_busctl_uninitchild(child));
1520 
1521 	case DDI_CTLOPS_REPORTDEV:
1522 		if (child_flavor_smp)
1523 			return (smp_busctl_reportdev(child));
1524 		else
1525 			return (scsi_busctl_reportdev(child));
1526 
1527 	case DDI_CTLOPS_IOMIN:
1528 		tran = ddi_get_driver_private(self);
1529 		ASSERT(tran);
1530 		if (tran == NULL)
1531 			return (DDI_FAILURE);
1532 
1533 		/*
1534 		 * The 'arg' value of nonzero indicates 'streaming'
1535 		 * mode. If in streaming mode, pick the largest
1536 		 * of our burstsizes available and say that that
1537 		 * is our minimum value (modulo what minxfer is).
1538 		 */
1539 		attr = &tran->tran_dma_attr;
1540 		val = *((int *)result);
1541 		val = maxbit(val, attr->dma_attr_minxfer);
1542 		*((int *)result) = maxbit(val, ((intptr_t)arg ?
1543 		    (1<<ddi_ffs(attr->dma_attr_burstsizes)-1) :
1544 		    (1<<(ddi_fls(attr->dma_attr_burstsizes)-1))));
1545 
1546 		return (ddi_ctlops(self, child, op, arg, result));
1547 
1548 	case DDI_CTLOPS_SIDDEV:
1549 		return (ndi_dev_is_persistent_node(child) ?
1550 		    DDI_SUCCESS : DDI_FAILURE);
1551 
1552 	/* XXX these should be handled */
1553 	case DDI_CTLOPS_POWER:
1554 	case DDI_CTLOPS_ATTACH:		/* DDI_PRE / DDI_POST attach */
1555 	case DDI_CTLOPS_DETACH:		/* DDI_PRE / DDI_POST detach */
1556 		return (DDI_SUCCESS);
1557 
1558 	/*
1559 	 * These ops correspond to functions that "shouldn't" be called
1560 	 * by a SCSI target driver. So we whine when we're called.
1561 	 */
1562 	case DDI_CTLOPS_DMAPMAPC:
1563 	case DDI_CTLOPS_REPORTINT:
1564 	case DDI_CTLOPS_REGSIZE:
1565 	case DDI_CTLOPS_NREGS:
1566 	case DDI_CTLOPS_SLAVEONLY:
1567 	case DDI_CTLOPS_AFFINITY:
1568 	case DDI_CTLOPS_POKE:
1569 	case DDI_CTLOPS_PEEK:
1570 		SCSI_HBA_LOG((_LOG(WARN, BUS_CTL), NULL, child,
1571 		    "invalid op (%d)", op));
1572 		return (DDI_FAILURE);
1573 
1574 	/* Everything else we pass up */
1575 	case DDI_CTLOPS_PTOB:
1576 	case DDI_CTLOPS_BTOP:
1577 	case DDI_CTLOPS_BTOPR:
1578 	case DDI_CTLOPS_DVMAPAGESIZE:
1579 	default:
1580 		return (ddi_ctlops(self, child, op, arg, result));
1581 	}
1582 }
1583 
1584 /*
1585  * Private wrapper for scsi_pkt's allocated via scsi_hba_pkt_alloc()
1586  */
1587 struct scsi_pkt_wrapper {
1588 	struct scsi_pkt		scsi_pkt;
1589 	int			pkt_wrapper_magic;
1590 	int			pkt_wrapper_len;
1591 };
1592 
1593 #if !defined(lint)
1594 _NOTE(SCHEME_PROTECTS_DATA("unique per thread", scsi_pkt_wrapper))
1595 _NOTE(SCHEME_PROTECTS_DATA("Unshared Data", dev_ops))
1596 #endif
1597 
1598 /*
1599  * Called by an HBA to allocate a scsi_pkt
1600  */
1601 /*ARGSUSED*/
1602 struct scsi_pkt *
1603 scsi_hba_pkt_alloc(
1604 	dev_info_t		*dip,
1605 	struct scsi_address	*ap,
1606 	int			cmdlen,
1607 	int			statuslen,
1608 	int			tgtlen,
1609 	int			hbalen,
1610 	int			(*callback)(caddr_t arg),
1611 	caddr_t			arg)
1612 {
1613 	struct scsi_pkt		*pkt;
1614 	struct scsi_pkt_wrapper	*hba_pkt;
1615 	caddr_t			p;
1616 	int			acmdlen, astatuslen, atgtlen, ahbalen;
1617 	int			pktlen;
1618 
1619 	/* Sanity check */
1620 	if (callback != SLEEP_FUNC && callback != NULL_FUNC)
1621 		SCSI_HBA_LOG((_LOG(WARN, PKT_ALLOC), dip, NULL,
1622 		    "callback must be either SLEEP_FUNC or NULL_FUNC"));
1623 
1624 	/*
1625 	 * Round up so everything gets allocated on long-word boundaries
1626 	 */
1627 	acmdlen = ROUNDUP(cmdlen);
1628 	astatuslen = ROUNDUP(statuslen);
1629 	atgtlen = ROUNDUP(tgtlen);
1630 	ahbalen = ROUNDUP(hbalen);
1631 	pktlen = sizeof (struct scsi_pkt_wrapper) +
1632 	    acmdlen + astatuslen + atgtlen + ahbalen;
1633 
1634 	hba_pkt = kmem_zalloc(pktlen,
1635 	    (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP);
1636 	if (hba_pkt == NULL) {
1637 		ASSERT(callback == NULL_FUNC);
1638 		return (NULL);
1639 	}
1640 
1641 	/*
1642 	 * Set up our private info on this pkt
1643 	 */
1644 	hba_pkt->pkt_wrapper_len = pktlen;
1645 	hba_pkt->pkt_wrapper_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
1646 	pkt = &hba_pkt->scsi_pkt;
1647 
1648 	/*
1649 	 * Set up pointers to private data areas, cdb, and status.
1650 	 */
1651 	p = (caddr_t)(hba_pkt + 1);
1652 	if (hbalen > 0) {
1653 		pkt->pkt_ha_private = (opaque_t)p;
1654 		p += ahbalen;
1655 	}
1656 	if (tgtlen > 0) {
1657 		pkt->pkt_private = (opaque_t)p;
1658 		p += atgtlen;
1659 	}
1660 	if (statuslen > 0) {
1661 		pkt->pkt_scbp = (uchar_t *)p;
1662 		p += astatuslen;
1663 	}
1664 	if (cmdlen > 0) {
1665 		pkt->pkt_cdbp = (uchar_t *)p;
1666 	}
1667 
1668 	/*
1669 	 * Initialize the pkt's scsi_address
1670 	 */
1671 	pkt->pkt_address = *ap;
1672 
1673 	/*
1674 	 * NB: It may not be safe for drivers, esp target drivers, to depend
1675 	 * on the following fields being set until all the scsi_pkt
1676 	 * allocation violations discussed in scsi_pkt.h are all resolved.
1677 	 */
1678 	pkt->pkt_cdblen = cmdlen;
1679 	pkt->pkt_tgtlen = tgtlen;
1680 	pkt->pkt_scblen = statuslen;
1681 
1682 	return (pkt);
1683 }
1684 
1685 /*
1686  * Called by an HBA to free a scsi_pkt
1687  */
1688 /*ARGSUSED*/
1689 void
1690 scsi_hba_pkt_free(
1691 	struct scsi_address	*ap,
1692 	struct scsi_pkt		*pkt)
1693 {
1694 	kmem_free(pkt, ((struct scsi_pkt_wrapper *)pkt)->pkt_wrapper_len);
1695 }
1696 
1697 /*
1698  * Return 1 if the scsi_pkt used a proper allocator.
1699  *
1700  * The DDI does not allow a driver to allocate it's own scsi_pkt(9S), a
1701  * driver should not have *any* compiled in dependencies on "sizeof (struct
1702  * scsi_pkt)". While this has been the case for many years, a number of
1703  * drivers have still not been fixed. This function can be used to detect
1704  * improperly allocated scsi_pkt structures, and produce messages identifying
1705  * drivers that need to be fixed.
1706  *
1707  * While drivers in violation are being fixed, this function can also
1708  * be used by the framework to detect packets that violated allocation
1709  * rules.
1710  *
1711  * NB: It is possible, but very unlikely, for this code to return a false
1712  * positive (finding correct magic, but for wrong reasons).  Careful
1713  * consideration is needed for callers using this interface to condition
1714  * access to newer scsi_pkt fields (those after pkt_reason).
1715  *
1716  * NB: As an aid to minimizing the amount of work involved in 'fixing' legacy
1717  * drivers that violate scsi_*(9S) allocation rules, private
1718  * scsi_pkt_size()/scsi_size_clean() functions are available (see their
1719  * implementation for details).
1720  *
1721  * *** Non-legacy use of scsi_pkt_size() is discouraged. ***
1722  *
1723  * NB: When supporting broken HBA drivers is not longer a concern, this
1724  * code should be removed.
1725  */
1726 int
1727 scsi_pkt_allocated_correctly(struct scsi_pkt *pkt)
1728 {
1729 	struct scsi_pkt_wrapper	*hba_pkt = (struct scsi_pkt_wrapper *)pkt;
1730 	int	magic;
1731 	major_t	major;
1732 #ifdef	DEBUG
1733 	int	*pspwm, *pspcwm;
1734 
1735 	/*
1736 	 * We are getting scsi packets from two 'correct' wrapper schemes,
1737 	 * make sure we are looking at the same place in both to detect
1738 	 * proper allocation.
1739 	 */
1740 	pspwm = &((struct scsi_pkt_wrapper *)0)->pkt_wrapper_magic;
1741 	pspcwm = &((struct scsi_pkt_cache_wrapper *)0)->pcw_magic;
1742 	ASSERT(pspwm == pspcwm);
1743 #endif	/* DEBUG */
1744 
1745 
1746 	/*
1747 	 * Check to see if driver is scsi_size_clean(), assume it
1748 	 * is using the scsi_pkt_size() interface everywhere it needs to
1749 	 * if the driver indicates it is scsi_size_clean().
1750 	 */
1751 	major = ddi_driver_major(P_TO_TRAN(pkt)->tran_hba_dip);
1752 	if (devnamesp[major].dn_flags & DN_SCSI_SIZE_CLEAN)
1753 		return (1);		/* ok */
1754 
1755 	/*
1756 	 * Special case crossing a page boundary. If the scsi_pkt was not
1757 	 * allocated correctly, then accross a page boundary we have a
1758 	 * fault hazzard.
1759 	 */
1760 	if ((((uintptr_t)(&hba_pkt->scsi_pkt)) & MMU_PAGEMASK) ==
1761 	    (((uintptr_t)(&hba_pkt->pkt_wrapper_magic)) & MMU_PAGEMASK)) {
1762 		/* fastpath, no cross-page hazzard */
1763 		magic = hba_pkt->pkt_wrapper_magic;
1764 	} else {
1765 		/* add protection for cross-page hazzard */
1766 		if (ddi_peek32((dev_info_t *)NULL,
1767 		    &hba_pkt->pkt_wrapper_magic, &magic) == DDI_FAILURE) {
1768 			return (0);	/* violation */
1769 		}
1770 	}
1771 
1772 	/* properly allocated packet always has correct magic */
1773 	return ((magic == PKT_WRAPPER_MAGIC) ? 1 : 0);
1774 }
1775 
1776 /*
1777  * Private interfaces to simplify conversion of legacy drivers so they don't
1778  * depend on scsi_*(9S) size. Instead of using these private interface, HBA
1779  * drivers should use DDI sanctioned allocation methods:
1780  *
1781  *	scsi_pkt	Use scsi_hba_pkt_alloc(9F), or implement
1782  *			tran_setup_pkt(9E).
1783  *
1784  *	scsi_device	You are doing something strange/special, a scsi_device
1785  *			structure should only be allocated by scsi_hba.c
1786  *			initchild code or scsi_vhci.c code.
1787  *
1788  *	scsi_hba_tran	Use scsi_hba_tran_alloc(9F).
1789  */
1790 size_t
1791 scsi_pkt_size()
1792 {
1793 	return (sizeof (struct scsi_pkt));
1794 }
1795 
1796 size_t
1797 scsi_hba_tran_size()
1798 {
1799 	return (sizeof (scsi_hba_tran_t));
1800 }
1801 
1802 size_t
1803 scsi_device_size()
1804 {
1805 	return (sizeof (struct scsi_device));
1806 }
1807 
1808 /*
1809  * Legacy compliance to scsi_pkt(9S) allocation rules through use of
1810  * scsi_pkt_size() is detected by the 'scsi-size-clean' driver.conf property
1811  * or an HBA driver calling to scsi_size_clean() from attach(9E).  A driver
1812  * developer should only indicate that a legacy driver is clean after using
1813  * SCSI_SIZE_CLEAN_VERIFY to ensure compliance (see scsi_pkt.h).
1814  */
1815 void
1816 scsi_size_clean(dev_info_t *dip)
1817 {
1818 	major_t		major;
1819 	struct devnames	*dnp;
1820 
1821 	ASSERT(dip);
1822 	major = ddi_driver_major(dip);
1823 	ASSERT(major < devcnt);
1824 	if (major >= devcnt) {
1825 		cmn_err(CE_WARN, "scsi_pkt_size: bogus major: %d", major);
1826 		return;
1827 	}
1828 
1829 	/* Set DN_SCSI_SIZE_CLEAN flag in dn_flags. */
1830 	dnp = &devnamesp[major];
1831 	if ((dnp->dn_flags & DN_SCSI_SIZE_CLEAN) == 0) {
1832 		LOCK_DEV_OPS(&dnp->dn_lock);
1833 		dnp->dn_flags |= DN_SCSI_SIZE_CLEAN;
1834 		UNLOCK_DEV_OPS(&dnp->dn_lock);
1835 	}
1836 }
1837 
1838 
1839 /*
1840  * Called by an HBA to map strings to capability indices
1841  */
1842 int
1843 scsi_hba_lookup_capstr(
1844 	char			*capstr)
1845 {
1846 	/*
1847 	 * Capability strings: only add entries to mask the legacy
1848 	 * '_' vs. '-' misery.  All new capabilities should use '-',
1849 	 * and be captured be added to SCSI_CAP_ASCII.
1850 	 */
1851 	static struct cap_strings {
1852 		char	*cap_string;
1853 		int	cap_index;
1854 	} cap_strings[] = {
1855 		{ "dma_max",		SCSI_CAP_DMA_MAX		},
1856 		{ "msg_out",		SCSI_CAP_MSG_OUT		},
1857 		{ "wide_xfer",		SCSI_CAP_WIDE_XFER		},
1858 		{ NULL,			0				}
1859 	};
1860 	static char		*cap_ascii[] = SCSI_CAP_ASCII;
1861 	char			**cap;
1862 	int			i;
1863 	struct cap_strings	*cp;
1864 
1865 	for (cap = cap_ascii, i = 0; *cap != NULL; cap++, i++)
1866 		if (strcmp(*cap, capstr) == 0)
1867 			return (i);
1868 
1869 	for (cp = cap_strings; cp->cap_string != NULL; cp++)
1870 		if (strcmp(cp->cap_string, capstr) == 0)
1871 			return (cp->cap_index);
1872 
1873 	return (-1);
1874 }
1875 
1876 /*
1877  * Called by an HBA to determine if the system is in 'panic' state.
1878  */
1879 int
1880 scsi_hba_in_panic()
1881 {
1882 	return (panicstr != NULL);
1883 }
1884 
1885 /*
1886  * If a SCSI target driver attempts to mmap memory,
1887  * the buck stops here.
1888  */
1889 /*ARGSUSED*/
1890 static int
1891 scsi_hba_map_fault(
1892 	dev_info_t		*dip,
1893 	dev_info_t		*child,
1894 	struct hat		*hat,
1895 	struct seg		*seg,
1896 	caddr_t			addr,
1897 	struct devpage		*dp,
1898 	pfn_t			pfn,
1899 	uint_t			prot,
1900 	uint_t			lock)
1901 {
1902 	return (DDI_FAILURE);
1903 }
1904 
1905 static int
1906 scsi_hba_get_eventcookie(
1907 	dev_info_t		*self,
1908 	dev_info_t		*child,
1909 	char			*name,
1910 	ddi_eventcookie_t	*eventp)
1911 {
1912 	scsi_hba_tran_t		*tran;
1913 
1914 	tran = ddi_get_driver_private(self);
1915 	if (tran->tran_get_eventcookie &&
1916 	    ((*tran->tran_get_eventcookie)(self,
1917 	    child, name, eventp) == DDI_SUCCESS)) {
1918 		return (DDI_SUCCESS);
1919 	}
1920 
1921 	return (ndi_busop_get_eventcookie(self, child, name, eventp));
1922 }
1923 
1924 static int
1925 scsi_hba_add_eventcall(
1926 	dev_info_t		*self,
1927 	dev_info_t		*child,
1928 	ddi_eventcookie_t	event,
1929 	void			(*callback)(
1930 					dev_info_t *self,
1931 					ddi_eventcookie_t event,
1932 					void *arg,
1933 					void *bus_impldata),
1934 	void			*arg,
1935 	ddi_callback_id_t	*cb_id)
1936 {
1937 	scsi_hba_tran_t		*tran;
1938 
1939 	tran = ddi_get_driver_private(self);
1940 	if (tran->tran_add_eventcall &&
1941 	    ((*tran->tran_add_eventcall)(self, child,
1942 	    event, callback, arg, cb_id) == DDI_SUCCESS)) {
1943 		return (DDI_SUCCESS);
1944 	}
1945 
1946 	return (DDI_FAILURE);
1947 }
1948 
1949 static int
1950 scsi_hba_remove_eventcall(dev_info_t *self, ddi_callback_id_t cb_id)
1951 {
1952 	scsi_hba_tran_t		*tran;
1953 	ASSERT(cb_id);
1954 
1955 	tran = ddi_get_driver_private(self);
1956 	if (tran->tran_remove_eventcall &&
1957 	    ((*tran->tran_remove_eventcall)(
1958 	    self, cb_id) == DDI_SUCCESS)) {
1959 		return (DDI_SUCCESS);
1960 	}
1961 
1962 	return (DDI_FAILURE);
1963 }
1964 
1965 static int
1966 scsi_hba_post_event(
1967 	dev_info_t		*self,
1968 	dev_info_t		*child,
1969 	ddi_eventcookie_t	event,
1970 	void			*bus_impldata)
1971 {
1972 	scsi_hba_tran_t		*tran;
1973 
1974 	tran = ddi_get_driver_private(self);
1975 	if (tran->tran_post_event &&
1976 	    ((*tran->tran_post_event)(self,
1977 	    child, event, bus_impldata) == DDI_SUCCESS)) {
1978 		return (DDI_SUCCESS);
1979 	}
1980 
1981 	return (DDI_FAILURE);
1982 }
1983 
1984 /*
1985  * Default getinfo(9e) for scsi_hba
1986  */
1987 /* ARGSUSED */
1988 static int
1989 scsi_hba_info(dev_info_t *self, ddi_info_cmd_t infocmd, void *arg,
1990     void **result)
1991 {
1992 	int error = DDI_SUCCESS;
1993 
1994 	switch (infocmd) {
1995 	case DDI_INFO_DEVT2INSTANCE:
1996 		*result = (void *)(intptr_t)(MINOR2INST(getminor((dev_t)arg)));
1997 		break;
1998 	default:
1999 		error = DDI_FAILURE;
2000 	}
2001 	return (error);
2002 }
2003 
2004 /*
2005  * Default open and close routine for scsi_hba
2006  */
2007 /* ARGSUSED */
2008 int
2009 scsi_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
2010 {
2011 	dev_info_t	*self;
2012 	scsi_hba_tran_t	*tran;
2013 	int		rv = 0;
2014 
2015 	if (otyp != OTYP_CHR)
2016 		return (EINVAL);
2017 
2018 	if ((self = e_ddi_hold_devi_by_dev(*devp, 0)) == NULL)
2019 		return (ENXIO);
2020 
2021 	tran = ddi_get_driver_private(self);
2022 	if (tran == NULL) {
2023 		ddi_release_devi(self);
2024 		return (ENXIO);
2025 	}
2026 
2027 	/*
2028 	 * tran_open_flag bit field:
2029 	 *	0:	closed
2030 	 *	1:	shared open by minor at bit position
2031 	 *	1 at 31st bit:	exclusive open
2032 	 */
2033 	mutex_enter(&(tran->tran_open_lock));
2034 	if (flags & FEXCL) {
2035 		if (tran->tran_open_flag != 0) {
2036 			rv = EBUSY;		/* already open */
2037 		} else {
2038 			tran->tran_open_flag = TRAN_OPEN_EXCL;
2039 		}
2040 	} else {
2041 		if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
2042 			rv = EBUSY;		/* already excl. open */
2043 		} else {
2044 			int minor = getminor(*devp) & TRAN_MINOR_MASK;
2045 			tran->tran_open_flag |= (1 << minor);
2046 			/*
2047 			 * Ensure that the last framework reserved minor
2048 			 * is unused. Otherwise, the exclusive open
2049 			 * mechanism may break.
2050 			 */
2051 			ASSERT(minor != 31);
2052 		}
2053 	}
2054 	mutex_exit(&(tran->tran_open_lock));
2055 
2056 	ddi_release_devi(self);
2057 	return (rv);
2058 }
2059 
2060 /* ARGSUSED */
2061 int
2062 scsi_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
2063 {
2064 	dev_info_t	*self;
2065 	scsi_hba_tran_t	*tran;
2066 
2067 	if (otyp != OTYP_CHR)
2068 		return (EINVAL);
2069 
2070 	if ((self = e_ddi_hold_devi_by_dev(dev, 0)) == NULL)
2071 		return (ENXIO);
2072 
2073 	tran = ddi_get_driver_private(self);
2074 	if (tran == NULL) {
2075 		ddi_release_devi(self);
2076 		return (ENXIO);
2077 	}
2078 
2079 	mutex_enter(&(tran->tran_open_lock));
2080 	if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
2081 		tran->tran_open_flag = 0;
2082 	} else {
2083 		int minor = getminor(dev) & TRAN_MINOR_MASK;
2084 		tran->tran_open_flag &= ~(1 << minor);
2085 	}
2086 	mutex_exit(&(tran->tran_open_lock));
2087 
2088 	ddi_release_devi(self);
2089 	return (0);
2090 }
2091 
2092 /*
2093  * standard ioctl commands for SCSI hotplugging
2094  */
2095 /* ARGSUSED */
2096 int
2097 scsi_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
2098 	int *rvalp)
2099 {
2100 	dev_info_t		*self;
2101 	struct devctl_iocdata	*dcp = NULL;
2102 	dev_info_t		*child = NULL;
2103 	struct scsi_device	*sd;
2104 	scsi_hba_tran_t		*tran;
2105 	uint_t			bus_state;
2106 	int			rv = 0;
2107 	int			circ;
2108 
2109 	if ((self = e_ddi_hold_devi_by_dev(dev, 0)) == NULL) {
2110 		rv = ENXIO;
2111 		goto out;
2112 	}
2113 
2114 	if ((tran = ddi_get_driver_private(self)) == NULL) {
2115 		rv = ENXIO;
2116 		goto out;
2117 	}
2118 
2119 	/* Ioctls for which the generic implementation suffices. */
2120 	switch (cmd) {
2121 	case DEVCTL_DEVICE_GETSTATE:
2122 	case DEVCTL_DEVICE_ONLINE:
2123 	case DEVCTL_DEVICE_OFFLINE:
2124 	case DEVCTL_DEVICE_REMOVE:
2125 	case DEVCTL_BUS_GETSTATE:
2126 		rv = ndi_devctl_ioctl(self, cmd, arg, mode, 0);
2127 		goto out;
2128 	}
2129 
2130 	/* read devctl ioctl data */
2131 	if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS) {
2132 		rv = EFAULT;
2133 		goto out;
2134 	}
2135 
2136 	/* Ioctls that require child identification */
2137 	switch (cmd) {
2138 	case DEVCTL_DEVICE_RESET:
2139 		/* child identification from unit-address */
2140 		if (ndi_dc_getname(dcp) == NULL ||
2141 		    ndi_dc_getaddr(dcp) == NULL) {
2142 			rv = EINVAL;
2143 			goto out;
2144 		}
2145 
2146 		ndi_devi_enter(self, &circ);
2147 		child = ndi_devi_find(self,
2148 		    ndi_dc_getname(dcp), ndi_dc_getaddr(dcp));
2149 		if (child == NULL) {
2150 			ndi_devi_exit(self, circ);
2151 			rv = ENXIO;
2152 			goto out;
2153 		}
2154 		ndi_hold_devi(child);
2155 		ndi_devi_exit(self, circ);
2156 		break;
2157 
2158 	case DEVCTL_BUS_RESETALL:
2159 		/*
2160 		 * Find a child's scsi_address so we can invoke tran_reset
2161 		 * below.
2162 		 *
2163 		 * XXX If no child exists, one may to able to fake a child.
2164 		 *	This will be a enhancement for the future.
2165 		 *	For now, we fall back to BUS_RESET.
2166 		 * XXX We sould be looking at node state to get one
2167 		 *	that is initialized...
2168 		 */
2169 		ndi_devi_enter(self, &circ);
2170 		child = ddi_get_child(self);
2171 		sd = NULL;
2172 		while (child) {
2173 			/* XXX verify scsi_device 'flavor' of child */
2174 			if ((sd = ddi_get_driver_private(child)) != NULL) {
2175 				ndi_hold_devi(child);
2176 				break;
2177 			}
2178 			child = ddi_get_next_sibling(child);
2179 		}
2180 		ndi_devi_exit(self, circ);
2181 		break;
2182 	}
2183 
2184 	switch (cmd) {
2185 	case DEVCTL_DEVICE_RESET:
2186 		ASSERT(child);
2187 		if (tran->tran_reset == NULL)
2188 			rv = ENOTSUP;
2189 		else {
2190 			sd = ddi_get_driver_private(child);
2191 			/* XXX verify scsi_device 'flavor' of child */
2192 			if ((sd == NULL) ||
2193 			    (tran->tran_reset(&sd->sd_address,
2194 			    RESET_TARGET) != 1))
2195 				rv = EIO;
2196 		}
2197 		break;
2198 
2199 	case DEVCTL_BUS_QUIESCE:
2200 		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
2201 		    (bus_state == BUS_QUIESCED))
2202 			rv = EALREADY;
2203 		else if (tran->tran_quiesce == NULL)
2204 			rv = ENOTSUP;
2205 		else if ((*tran->tran_quiesce)(self) != 0)
2206 			rv = EIO;
2207 		else
2208 			(void) ndi_set_bus_state(self, BUS_QUIESCED);
2209 		break;
2210 
2211 	case DEVCTL_BUS_UNQUIESCE:
2212 		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
2213 		    (bus_state == BUS_ACTIVE))
2214 			rv = EALREADY;
2215 		else if (tran->tran_unquiesce == NULL)
2216 			rv = ENOTSUP;
2217 		else if ((*tran->tran_unquiesce)(self) != 0)
2218 			rv = EIO;
2219 		else
2220 			(void) ndi_set_bus_state(self, BUS_ACTIVE);
2221 		break;
2222 
2223 	case DEVCTL_BUS_RESET:
2224 		if (tran->tran_bus_reset == NULL)
2225 			rv = ENOTSUP;
2226 		else if ((*tran->tran_bus_reset)(self, RESET_BUS) != 1)
2227 			rv = EIO;
2228 		break;
2229 
2230 	case DEVCTL_BUS_RESETALL:
2231 		if (tran->tran_reset == NULL) {
2232 			rv = ENOTSUP;
2233 		} else {
2234 			if (sd) {
2235 				if ((*tran->tran_reset)
2236 				    (&sd->sd_address, RESET_ALL) != 1)
2237 					rv = EIO;
2238 			} else {
2239 				if ((tran->tran_bus_reset == NULL) ||
2240 				    ((*tran->tran_bus_reset)
2241 				    (self, RESET_BUS) != 1))
2242 					rv = EIO;
2243 			}
2244 		}
2245 		break;
2246 
2247 	case DEVCTL_BUS_CONFIGURE:
2248 		if (ndi_devi_config(self, NDI_DEVFS_CLEAN|
2249 		    NDI_DEVI_PERSIST|NDI_CONFIG_REPROBE) != NDI_SUCCESS) {
2250 			rv = EIO;
2251 		}
2252 		break;
2253 
2254 	case DEVCTL_BUS_UNCONFIGURE:
2255 		if (ndi_devi_unconfig(self,
2256 		    NDI_DEVI_REMOVE|NDI_DEVFS_CLEAN) != NDI_SUCCESS) {
2257 			rv = EBUSY;
2258 		}
2259 		break;
2260 
2261 	default:
2262 		rv = ENOTTY;
2263 	}
2264 
2265 out:	if (child)
2266 		ndi_rele_devi(child);
2267 	if (dcp)
2268 		ndi_dc_freehdl(dcp);
2269 	if (self)
2270 		ddi_release_devi(self);
2271 	return (rv);
2272 }
2273 
2274 /*ARGSUSED*/
2275 static int
2276 scsi_hba_fm_init_child(dev_info_t *self, dev_info_t *child, int cap,
2277     ddi_iblock_cookie_t *ibc)
2278 {
2279 	scsi_hba_tran_t	*tran = ddi_get_driver_private(self);
2280 
2281 	return (tran ? tran->tran_fm_capable : scsi_fm_capable);
2282 }
2283 
2284 static int
2285 scsi_hba_bus_power(dev_info_t *self, void *impl_arg, pm_bus_power_op_t op,
2286     void *arg, void *result)
2287 {
2288 	scsi_hba_tran_t	*tran;
2289 
2290 	tran = ddi_get_driver_private(self);
2291 	if (tran && tran->tran_bus_power) {
2292 		return (tran->tran_bus_power(self, impl_arg,
2293 		    op, arg, result));
2294 	}
2295 
2296 	return (pm_busop_bus_power(self, impl_arg, op, arg, result));
2297 }
2298 
2299 /*
2300  * Convert between normalized (SCSI-3) LUN format, as described by
2301  * scsi_lun_t, and a normalized lun64_t representation. The normalized
2302  * representation maps in a compatible way to SCSI-2 LUNs.
2303  *
2304  * SCSI-3 LUNs are 64 bits. SCSI-2 LUNs are 3 bits (up to 5 bits in
2305  * some non-compliant implementations). SCSI-3 will pass a (64-bit)
2306  * scsi_lun_t, but we need a representation from which we can for example,
2307  * make device names. For compatibility we represent 64-bit LUN numbers
2308  * in such a way that they appear like they would have under SCSI-2.
2309  * This means that the single level LUN number is in the lowest byte with
2310  * the second, third, and fourth level LUNs represented in successively
2311  * higher bytes. In particular, if (and only if) the first byte of a 64
2312  * bit LUN is zero, denoting "Peripheral Device Addressing Method" and
2313  * "Bus Identifier" zero, then the target implements LUNs compatible in
2314  * spirit with SCSI-2 LUNs (although under SCSI-3 there may be up to
2315  * 256 of them). Under SCSI-3 rules, a target is *required* to use
2316  * this format if it contains 256 or fewer Logical Units, none of which
2317  * are dependent logical units.
2318  *
2319  * These routines have knowledge of the structure and size of a scsi_lun_t.
2320  *
2321  * XXX Should these function be rewritten to take the scsi_lun_t *?
2322  */
2323 scsi_lun64_t
2324 scsi_lun_to_lun64(scsi_lun_t lun)
2325 {
2326 	scsi_lun64_t	lun64;
2327 
2328 	/* check address method and bus identifier */
2329 	if (lun.sl_lun1_msb == 0) {
2330 		/* single-level LUN */
2331 		lun64 = lun.sl_lun1_lsb;	/* extract the 8-bit LUN */
2332 
2333 		/* Ensure rest of LUN is zero, which it is supposed to be */
2334 		if ((lun.sl_lun2_msb == 0) && (lun.sl_lun2_lsb == 0) &&
2335 		    (lun.sl_lun3_msb == 0) && (lun.sl_lun3_lsb == 0) &&
2336 		    (lun.sl_lun4_msb == 0) && (lun.sl_lun4_lsb == 0)) {
2337 			return (lun64);
2338 		}
2339 
2340 		/* Oops, we got a bad scsi_lun_t. Leave it in 64-bit form */
2341 		SCSI_HBA_LOG((_LOG(DIAG1, BADLUN), NULL, NULL,
2342 		    "lun_to_lun64 bad lun %" PRIx64, *(scsi_lun64_t *)&lun));
2343 	}
2344 
2345 	/*
2346 	 * We have a big LUN that is not backward compatible.
2347 	 * Construct a 64 bit number using the right byte order.
2348 	 */
2349 	lun64 =
2350 	    ((scsi_lun64_t)lun.sl_lun1_msb << 56) |
2351 	    ((scsi_lun64_t)lun.sl_lun1_lsb << 48) |
2352 	    ((scsi_lun64_t)lun.sl_lun2_msb << 40) |
2353 	    ((scsi_lun64_t)lun.sl_lun2_lsb << 32) |
2354 	    ((scsi_lun64_t)lun.sl_lun3_msb << 24) |
2355 	    ((scsi_lun64_t)lun.sl_lun3_lsb << 16) |
2356 	    ((scsi_lun64_t)lun.sl_lun4_msb <<  8) |
2357 	    (scsi_lun64_t)lun.sl_lun4_lsb;
2358 	return (lun64);
2359 }
2360 
2361 scsi_lun_t
2362 scsi_lun64_to_lun(scsi_lun64_t lun64)
2363 {
2364 	scsi_lun_t	lun;
2365 
2366 	if (lun64 < 256) {
2367 		/* This LUN is in compatibility format */
2368 		lun.sl_lun1_msb = 0;
2369 		lun.sl_lun1_lsb = (uchar_t)lun64;
2370 		lun.sl_lun2_msb = 0;
2371 		lun.sl_lun2_lsb = 0;
2372 		lun.sl_lun3_msb = 0;
2373 		lun.sl_lun3_lsb = 0;
2374 		lun.sl_lun4_msb = 0;
2375 		lun.sl_lun4_lsb = 0;
2376 	} else {
2377 		/* This in full 64 bit LUN format */
2378 		lun.sl_lun1_msb = (uchar_t)(lun64 >> 56);
2379 		lun.sl_lun1_lsb = (uchar_t)(lun64 >> 48);
2380 		lun.sl_lun2_msb = (uchar_t)(lun64 >> 40);
2381 		lun.sl_lun2_lsb = (uchar_t)(lun64 >> 32);
2382 		lun.sl_lun3_msb = (uchar_t)(lun64 >> 24);
2383 		lun.sl_lun3_lsb = (uchar_t)(lun64 >> 16);
2384 		lun.sl_lun4_msb = (uchar_t)(lun64 >>  8);
2385 		lun.sl_lun4_lsb = (uchar_t)(lun64);
2386 
2387 		/* Oops, bad LUN -- this is required to be nonzero */
2388 		if (lun.sl_lun1_msb == 0)
2389 			SCSI_HBA_LOG((_LOG(DIAG1, BADLUN), NULL, NULL,
2390 			    "lun64_to_lun bad lun %" PRIlun64, lun64));
2391 	}
2392 	return (lun);
2393 }
2394 
2395 /*
2396  * Return the lun from an address string. Either the lun is after the
2397  * first ',' or the entire addr is the lun. Return SCSI_LUN64_ILLEGAL
2398  * if the format is incorrect.
2399  *
2400  * If the addr specified has incorrect syntax (busconfig one of
2401  * bogus /devices path) then scsi_addr_to_lun64 can return SCSI_LUN64_ILLEGAL.
2402  */
2403 scsi_lun64_t
2404 scsi_addr_to_lun64(char *addr)
2405 {
2406 	scsi_lun64_t	lun64;
2407 	char		*s;
2408 	int		i;
2409 
2410 	if (addr) {
2411 		s = strchr(addr, ',');			/* "addr,lun[,sfunc]" */
2412 		if (s)
2413 			s++;				/* skip ',' */
2414 		else
2415 			s = addr;			/* "lun" */
2416 
2417 		for (lun64 = 0, i = 0; *s && (i < 16); s++, i++) {
2418 			if (*s >= '0' && *s <= '9')
2419 				lun64 = (lun64 << 4) + (*s - '0');
2420 			else if (*s >= 'A' && *s <= 'F')
2421 				lun64 = (lun64 << 4) + 10 + (*s - 'A');
2422 			else if (*s >= 'a' && *s <= 'f')
2423 				lun64 = (lun64 << 4) + 10 + (*s - 'a');
2424 			else
2425 				break;
2426 		}
2427 		if (*s && (*s != ','))		/* addr,lun[,sfunc] is OK */
2428 			lun64 = SCSI_LUN64_ILLEGAL;
2429 	} else
2430 		lun64 = SCSI_LUN64_ILLEGAL;
2431 
2432 	if (lun64 == SCSI_LUN64_ILLEGAL)
2433 		SCSI_HBA_LOG((_LOG(DIAG2, BADLUN), NULL, NULL,
2434 		    "addr_to_lun64 %s lun %" PRIlun64,
2435 		    addr ? addr : "NULL", lun64));
2436 	return (lun64);
2437 }
2438 
2439 /*
2440  * Convert scsi ascii string data to NULL terminated (semi) legal IEEE 1275
2441  * "compatible" (name) property form.
2442  *
2443  * For ASCII INQUIRY data, a one-way conversion algorithm is needed to take
2444  * SCSI_ASCII (20h - 7Eh) to a 1275-like compatible form. The 1275 spec allows
2445  * letters, digits, one ",", and ". _ + -", all limited by a maximum 31
2446  * character length. Since ", ." are used as separators in the compatible
2447  * string itself, they are converted to "_". All SCSI_ASCII characters that
2448  * are illegal in 1275, as well as any illegal SCSI_ASCII characters
2449  * encountered, are converted to "_". To reduce length, trailing blanks are
2450  * trimmed from SCSI_ASCII fields prior to conversion.
2451  *
2452  * Example: SCSI_ASCII "ST32550W SUN2.1G" -> "ST32550W_SUN2_1G"
2453  *
2454  * NOTE: the 1275 string form is always less than or equal to the scsi form.
2455  */
2456 static char *
2457 string_scsi_to_1275(char *s_1275, char *s_scsi, int len)
2458 {
2459 	(void) strncpy(s_1275, s_scsi, len);
2460 	s_1275[len--] = '\0';
2461 
2462 	while (len >= 0) {
2463 		if (s_1275[len] == ' ')
2464 			s_1275[len--] = '\0';	/* trim trailing " " */
2465 		else
2466 			break;
2467 	}
2468 
2469 	while (len >= 0) {
2470 		if (((s_1275[len] >= 'a') && (s_1275[len] <= 'z')) ||
2471 		    ((s_1275[len] >= 'A') && (s_1275[len] <= 'Z')) ||
2472 		    ((s_1275[len] >= '0') && (s_1275[len] <= '9')) ||
2473 		    (s_1275[len] == '_') ||
2474 		    (s_1275[len] == '+') ||
2475 		    (s_1275[len] == '-'))
2476 			len--;			/* legal 1275  */
2477 		else
2478 			s_1275[len--] = '_';	/* illegal SCSI_ASCII | 1275 */
2479 	}
2480 
2481 	return (s_1275);
2482 }
2483 
2484 /*
2485  * Given the inquiry data, binding_set, and dtype_node for a scsi device,
2486  * return the nodename and compatible property for the device. The "compatible"
2487  * concept comes from IEEE-1275. The compatible information is returned is in
2488  * the correct form for direct use defining the "compatible" string array
2489  * property. Internally, "compatible" is also used to determine the nodename
2490  * to return.
2491  *
2492  * This function is provided as a separate entry point for use by drivers that
2493  * currently issue their own non-SCSA inquiry command and perform their own
2494  * node creation based their own private compiled in tables. Converting these
2495  * drivers to use this interface provides a quick easy way of obtaining
2496  * consistency as well as the flexibility associated with the 1275 techniques.
2497  *
2498  * The dtype_node is passed as a separate argument (instead of having the
2499  * implementation use inq_dtype). It indicates that information about
2500  * a secondary function embedded service should be produced.
2501  *
2502  * Callers must always use scsi_hba_nodename_compatible_free, even if
2503  * *nodenamep is null, to free the nodename and compatible information
2504  * when done.
2505  *
2506  * If a nodename can't be determined then **compatiblep will point to a
2507  * diagnostic string containing all the compatible forms.
2508  *
2509  * NOTE: some compatible strings may violate the 31 character restriction
2510  * imposed by IEEE-1275. This is not a problem because Solaris does not care
2511  * about this 31 character limit.
2512  *
2513  * Each compatible form belongs to a form-group.  The form-groups currently
2514  * defined are generic ("scsiclass"), binding-set ("scsa.b"), and failover
2515  * ("scsa.f").
2516  *
2517  * The following compatible forms, in high to low precedence
2518  * order, are defined for SCSI target device nodes.
2519  *
2520  *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(1 *1&2)
2521  *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(2 *1)
2522  *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(3 *2)
2523  *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(4)
2524  *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP	(5 *1&2)
2525  *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(6 *1)
2526  *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(7 *2)
2527  *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(8)
2528  *  scsa,DD.bBBBBBBBB					(8.5 *3)
2529  *  scsiclass,DDEEFFF					(9 *1&2)
2530  *  scsiclass,DDEE					(10 *1)
2531  *  scsiclass,DDFFF					(11 *2)
2532  *  scsiclass,DD					(12)
2533  *  scsa.fFFF						(12.5 *4)
2534  *  scsiclass						(13)
2535  *
2536  *	  *1 only produced on a secondary function node
2537  *	  *2 only produced when generic form-group flags exist.
2538  *	  *3 only produced when binding-set form-group legacy support is needed
2539  *	  *4 only produced when failover form-group flags exist.
2540  *
2541  *	where:
2542  *
2543  *	v                       is the letter 'v'. Denotest the
2544  *				beginning of VVVVVVVV.
2545  *
2546  *	VVVVVVVV                Translated scsi_vendor.
2547  *
2548  *	p                       is the letter 'p'. Denotes the
2549  *				beginning of PPPPPPPPPPPPPPPP.
2550  *
2551  *	PPPPPPPPPPPPPPPP	Translated scsi_product.
2552  *
2553  *	r                       is the letter 'r'. Denotes the
2554  *				beginning of RRRR.
2555  *
2556  *	RRRR                    Translated scsi_revision.
2557  *
2558  *	DD                      is a two digit ASCII hexadecimal
2559  *				number. The value of the two digits is
2560  *				based one the SCSI "Peripheral device
2561  *				type" command set associated with the
2562  *				node. On a primary node this is the
2563  *				scsi_dtype of the primary command set,
2564  *				on a secondary node this is the
2565  *				scsi_dtype associated with the embedded
2566  *				function command set.
2567  *
2568  *	EE                      Same encoding used for DD. This form is
2569  *				only generated on secondary function
2570  *				nodes. The DD function is embedded in
2571  *				an EE device.
2572  *
2573  *	FFF                     Concatenation, in alphabetical order,
2574  *				of the flag characters within a form-group.
2575  *				For a given form-group, the following
2576  *				flags are defined.
2577  *
2578  *				scsiclass: (generic form-group):
2579  *				  R	Removable_Media: Used when
2580  *					inq_rmb is set.
2581  *
2582  *				scsa.f:	(failover form-group):
2583  *				  E	Explicit Target_Port_Group: Used
2584  *					when inq_tpgse is set and 'G' is
2585  *					alse present.
2586  *				  G	GUID: Used when a GUID can be
2587  *					generated for the device.
2588  *				  I	Implicit Target_Port_Group: Used
2589  *					when inq_tpgs is set and 'G' is
2590  *					also present.
2591  *
2592  *				Forms using FFF are only be generated
2593  *				if there are applicable flag
2594  *				characters.
2595  *
2596  *	b                       is the letter 'b'. Denotes the
2597  *				beginning of BBBBBBBB.
2598  *
2599  *	BBBBBBBB                Binding-set. Operating System Specific:
2600  *				scsi-binding-set property of HBA.
2601  */
2602 #define	NCOMPAT		(1 + (13 + 2) + 1)
2603 #define	COMPAT_LONGEST	(strlen( \
2604 	"scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR" + 1))
2605 
2606 /*
2607  * Private version with extra device 'identity' arguments to allow code
2608  * to determine GUID FFF support.
2609  */
2610 static void
2611 scsi_hba_identity_nodename_compatible_get(struct scsi_inquiry *inq,
2612     uchar_t *inq80, size_t inq80len, uchar_t *inq83, size_t inq83len,
2613     char *binding_set, int dtype_node, char *compat0,
2614     char **nodenamep, char ***compatiblep, int *ncompatiblep)
2615 {
2616 	char		vid[sizeof (inq->inq_vid) + 1 ];
2617 	char		pid[sizeof (inq->inq_pid) + 1];
2618 	char		rev[sizeof (inq->inq_revision) + 1];
2619 	char		gf[sizeof ("R\0")];
2620 	char		ff[sizeof ("EGI\0")];
2621 	int		dtype_device;
2622 	int		ncompat;		/* number of compatible */
2623 	char		**compatp;		/* compatible ptrs */
2624 	int		i;
2625 	char		*nname;			/* nodename */
2626 	char		*dname;			/* driver name */
2627 	char		**csp;
2628 	char		*p;
2629 	int		tlen;
2630 	int		len;
2631 	major_t		major;
2632 	ddi_devid_t	devid;
2633 	char		*guid;
2634 
2635 	/*
2636 	 * Nodename_aliases: This table was originally designed to be
2637 	 * implemented via a new nodename_aliases file - a peer to the
2638 	 * driver_aliases that selects a nodename based on compatible
2639 	 * forms in much the same say driver_aliases is used to select
2640 	 * driver bindings from compatible forms. Each compatible form
2641 	 * is an 'alias'. Until a more general need for a
2642 	 * nodename_aliases file exists, which may never occur, the
2643 	 * scsi mappings are described here via a compiled in table.
2644 	 *
2645 	 * This table contains nodename mappings for self-identifying
2646 	 * scsi devices enumerated by the Solaris kernel. For a given
2647 	 * device, the highest precedence "compatible" form with a
2648 	 * mapping is used to select the nodename for the device. This
2649 	 * will typically be a generic nodename, however in some legacy
2650 	 * compatibility cases a driver nodename mapping may be selected.
2651 	 *
2652 	 * Because of possible breakage associated with switching SCSI
2653 	 * target devices from driver nodenames to generic nodenames,
2654 	 * we are currently unable to support generic nodenames for all
2655 	 * SCSI devices (binding-sets). Although /devices paths are
2656 	 * defined as unstable, avoiding possible breakage is
2657 	 * important. Some of the newer SCSI transports (USB) already
2658 	 * use generic nodenames. All new SCSI transports and target
2659 	 * devices should use generic nodenames. At times this decision
2660 	 * may be architecture dependent (sparc .vs. intel) based on when
2661 	 * a transport was supported on a particular architecture.
2662 	 *
2663 	 * We provide a base set of generic nodename mappings based on
2664 	 * scsiclass dtype and higher-precedence driver nodename
2665 	 * mappings based on scsa "binding-set" to cover legacy
2666 	 * issues. The binding-set is typically associated with
2667 	 * "scsi-binding-set" property value of the HBA. The legacy
2668 	 * mappings are provided independent of whether the driver they
2669 	 * refer to is installed. This allows a correctly named node
2670 	 * be created at discovery time, and binding to occur when/if
2671 	 * an add_drv of the legacy driver occurs.
2672 	 *
2673 	 * We also have mappings for legacy SUN hardware that
2674 	 * misidentifies itself (enclosure services which identify
2675 	 * themselves as processors). All future hardware should use
2676 	 * the correct dtype.
2677 	 *
2678 	 * As SCSI HBAs are modified to use the SCSA interfaces for
2679 	 * self-identifying SCSI target devices (PSARC/2004/116) the
2680 	 * nodename_aliases table (PSARC/2004/420) should be augmented
2681 	 * with legacy mappings in order to maintain compatibility with
2682 	 * existing /devices paths, especially for devices that house
2683 	 * an OS. Failure to do this may cause upgrade problems.
2684 	 * Additions for new target devices or transports should not
2685 	 * add scsa binding-set compatible mappings.
2686 	 */
2687 	static struct nodename_aliases {
2688 		char	*na_nodename;		/* nodename */
2689 		char	*na_alias;		/* compatible form match */
2690 	} na[] = {
2691 	/* # mapping to generic nodenames based on scsi dtype */
2692 		{"disk",		"scsiclass,00"},
2693 		{"tape",		"scsiclass,01"},
2694 		{"printer",		"scsiclass,02"},
2695 		{"processor",		"scsiclass,03"},
2696 		{"worm",		"scsiclass,04"},
2697 		{"cdrom",		"scsiclass,05"},
2698 		{"scanner",		"scsiclass,06"},
2699 		{"optical-disk",	"scsiclass,07"},
2700 		{"medium-changer",	"scsiclass,08"},
2701 		{"obsolete",		"scsiclass,09"},
2702 		{"prepress-a",		"scsiclass,0a"},
2703 		{"prepress-b",		"scsiclass,0b"},
2704 		{"array-controller",	"scsiclass,0c"},
2705 		{"enclosure",		"scsiclass,0d"},
2706 		{"disk",		"scsiclass,0e"},
2707 		{"card-reader",		"scsiclass,0f"},
2708 		{"bridge",		"scsiclass,10"},
2709 		{"object-store",	"scsiclass,11"},
2710 		{"reserved",		"scsiclass,12"},
2711 		{"reserved",		"scsiclass,13"},
2712 		{"reserved",		"scsiclass,14"},
2713 		{"reserved",		"scsiclass,15"},
2714 		{"reserved",		"scsiclass,16"},
2715 		{"reserved",		"scsiclass,17"},
2716 		{"reserved",		"scsiclass,18"},
2717 		{"reserved",		"scsiclass,19"},
2718 		{"reserved",		"scsiclass,1a"},
2719 		{"reserved",		"scsiclass,1b"},
2720 		{"reserved",		"scsiclass,1c"},
2721 		{"reserved",		"scsiclass,1d"},
2722 		{"well-known-lun",	"scsiclass,1e"},
2723 		{"unknown",		"scsiclass,1f"},
2724 
2725 #ifdef	sparc
2726 	/* # legacy mapping to driver nodenames for fcp binding-set */
2727 		{"ssd",			"scsa,00.bfcp"},
2728 		{"st",			"scsa,01.bfcp"},
2729 		{"sgen",		"scsa,08.bfcp"},
2730 		{"ses",			"scsa,0d.bfcp"},
2731 
2732 	/* # legacy mapping to driver nodenames for vhci binding-set */
2733 		{"ssd",			"scsa,00.bvhci"},
2734 		{"st",			"scsa,01.bvhci"},
2735 		{"sgen",		"scsa,08.bvhci"},
2736 		{"ses",			"scsa,0d.bvhci"},
2737 #else	/* sparc */
2738 	/* # for x86 fcp and vhci use generic nodenames */
2739 #endif	/* sparc */
2740 
2741 #ifdef  notdef
2742 	/*
2743 	 * The following binding-set specific mappings are not being
2744 	 * delivered at this time, but are listed here as an examples of
2745 	 * the type of mappings needed.
2746 	 */
2747 
2748 	/* # legacy mapping to driver nodenames for spi binding-set */
2749 		{"sd",			"scsa,00.bspi"},
2750 		{"sd",			"scsa,05.bspi"},
2751 		{"sd",			"scsa,07.bspi"},
2752 		{"st",			"scsa,01.bspi"},
2753 		{"ses",			"scsa,0d.bspi"},
2754 
2755 	/* #				SUN misidentified spi hardware */
2756 		{"ses",			"scsiclass,03.vSUN.pD2"},
2757 		{"ses",			"scsiclass,03.vSYMBIOS.pD1000"},
2758 
2759 	/* # legacy mapping to driver nodenames for atapi binding-set */
2760 		{"sd",			"scsa,00.batapi"},
2761 		{"sd",			"scsa,05.batapi"},
2762 		{"sd",			"scsa,07.batapi"},
2763 		{"st",			"scsa,01.batapi"},
2764 		{"unknown",		"scsa,0d.batapi"},
2765 
2766 	/* # legacy mapping to generic nodenames for usb binding-set */
2767 		{"disk",		"scsa,05.busb"},
2768 		{"disk",		"scsa,07.busb"},
2769 		{"changer",		"scsa,08.busb"},
2770 		{"comm",		"scsa,09.busb"},
2771 		{"array_ctlr",		"scsa,0c.busb"},
2772 		{"esi",			"scsa,0d.busb"},
2773 #endif  /* notdef */
2774 
2775 	/*
2776 	 * mapping nodenames for mpt based on scsi dtype
2777 	 * for being compatible with the original node names
2778 	 * under mpt controller
2779 	 */
2780 		{"sd",			"scsa,00.bmpt"},
2781 		{"sd",			"scsa,05.bmpt"},
2782 		{"sd",			"scsa,07.bmpt"},
2783 		{"st",			"scsa,01.bmpt"},
2784 		{"ses",			"scsa,0d.bmpt"},
2785 		{"sgen",		"scsa,08.bmpt"},
2786 		{NULL,		NULL}
2787 	};
2788 	struct nodename_aliases *nap;
2789 
2790 	ASSERT(nodenamep && compatiblep && ncompatiblep &&
2791 	    (binding_set == NULL || (strlen(binding_set) <= 8)));
2792 	if ((nodenamep == NULL) || (compatiblep == NULL) ||
2793 	    (ncompatiblep == NULL))
2794 		return;
2795 
2796 	/*
2797 	 * In order to reduce runtime we allocate one block of memory that
2798 	 * contains both the NULL terminated array of pointers to compatible
2799 	 * forms and the individual compatible strings. This block is
2800 	 * somewhat larger than needed, but is short lived - it only exists
2801 	 * until the caller can transfer the information into the "compatible"
2802 	 * string array property and call scsi_hba_nodename_compatible_free.
2803 	 */
2804 	tlen = NCOMPAT * COMPAT_LONGEST;
2805 	compatp = kmem_alloc((NCOMPAT * sizeof (char *)) + tlen, KM_SLEEP);
2806 
2807 	/* convert inquiry data from SCSI ASCII to 1275 string */
2808 	(void) string_scsi_to_1275(vid, inq->inq_vid,
2809 	    sizeof (inq->inq_vid));
2810 	(void) string_scsi_to_1275(pid, inq->inq_pid,
2811 	    sizeof (inq->inq_pid));
2812 	(void) string_scsi_to_1275(rev, inq->inq_revision,
2813 	    sizeof (inq->inq_revision));
2814 	ASSERT((strlen(vid) <= sizeof (inq->inq_vid)) &&
2815 	    (strlen(pid) <= sizeof (inq->inq_pid)) &&
2816 	    (strlen(rev) <= sizeof (inq->inq_revision)));
2817 
2818 	/*
2819 	 * Form flags in ***ALPHABETICAL*** order within form-group:
2820 	 *
2821 	 * NOTE: When adding a new flag to an existing form-group, carefull
2822 	 * consideration must be given to not breaking existing bindings
2823 	 * based on that form-group.
2824 	 */
2825 
2826 	/*
2827 	 * generic form-group flags
2828 	 *   R	removable:
2829 	 *	Set when inq_rmb is set and for well known scsi dtypes. For a
2830 	 *	bus where the entire device is removable (like USB), we expect
2831 	 *	the HBA to intercept the inquiry data and set inq_rmb.
2832 	 *	Since OBP does not distinguish removable media in its generic
2833 	 *	name selection we avoid setting the 'R' flag if the root is not
2834 	 *	yet mounted.
2835 	 */
2836 	i = 0;
2837 	dtype_device = inq->inq_dtype & DTYPE_MASK;
2838 	if (rootvp && (inq->inq_rmb ||
2839 	    (dtype_device == DTYPE_WORM) ||
2840 	    (dtype_device == DTYPE_RODIRECT) ||
2841 	    (dtype_device == DTYPE_OPTICAL)))
2842 		gf[i++] = 'R';			/* removable */
2843 	gf[i] = '\0';
2844 
2845 	/*
2846 	 * failover form-group flags
2847 	 *   E	Explicit Target_Port_Group_Supported:
2848 	 *	Set for a device that has a GUID if inq_tpgse also set.
2849 	 *   G	GUID:
2850 	 *	Set when we have identity information, can determine a devid
2851 	 *	from the identity information, and can generate a guid from
2852 	 *	that devid.
2853 	 *   I	Implicit Target_Port_Group_Supported:
2854 	 *	Set for a device that has a GUID if inq_tpgs also set.
2855 	 */
2856 	i = 0;
2857 	if ((inq80 || inq83) &&
2858 	    (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST, NULL,
2859 	    (uchar_t *)inq, sizeof (*inq), inq80, inq80len, inq83, inq83len,
2860 	    &devid) == DDI_SUCCESS)) {
2861 		guid = ddi_devid_to_guid(devid);
2862 		ddi_devid_free(devid);
2863 	} else
2864 		guid = NULL;
2865 	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_EXPLICIT))
2866 		ff[i++] = 'E';			/* EXPLICIT TPGS */
2867 	if (guid)
2868 		ff[i++] = 'G';			/* GUID */
2869 	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_IMPLICIT))
2870 		ff[i++] = 'I';			/* IMPLICIT TPGS */
2871 	ff[i] = '\0';
2872 	if (guid)
2873 		ddi_devid_free_guid(guid);
2874 
2875 	/*
2876 	 * Construct all applicable compatible forms. See comment at the
2877 	 * head of the function for a description of the compatible forms.
2878 	 */
2879 	csp = compatp;
2880 	p = (char *)(compatp + NCOMPAT);
2881 
2882 	/* ( 0) driver (optional, not documented in scsi(4)) */
2883 	if (compat0) {
2884 		*csp++ = p;
2885 		(void) snprintf(p, tlen, "%s", compat0);
2886 		len = strlen(p) + 1;
2887 		p += len;
2888 		tlen -= len;
2889 	}
2890 
2891 	/* ( 1) scsiclass,DDEEFFF.vV.pP.rR */
2892 	if ((dtype_device != dtype_node) && *gf && *vid && *pid && *rev) {
2893 		*csp++ = p;
2894 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s.r%s",
2895 		    dtype_node, dtype_device, gf, vid, pid, rev);
2896 		len = strlen(p) + 1;
2897 		p += len;
2898 		tlen -= len;
2899 	}
2900 
2901 	/* ( 2) scsiclass,DDEE.vV.pP.rR */
2902 	if ((dtype_device != dtype_node) && *vid && *pid && *rev) {
2903 		*csp++ = p;
2904 		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s.r%s",
2905 		    dtype_node, dtype_device, vid, pid, rev);
2906 		len = strlen(p) + 1;
2907 		p += len;
2908 		tlen -= len;
2909 	}
2910 
2911 	/* ( 3) scsiclass,DDFFF.vV.pP.rR */
2912 	if (*gf && *vid && *pid && *rev) {
2913 		*csp++ = p;
2914 		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s.r%s",
2915 		    dtype_node, gf, vid, pid, rev);
2916 		len = strlen(p) + 1;
2917 		p += len;
2918 		tlen -= len;
2919 	}
2920 
2921 	/* ( 4) scsiclass,DD.vV.pP.rR */
2922 	if (*vid && *pid && rev) {
2923 		*csp++ = p;
2924 		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s.r%s",
2925 		    dtype_node, vid, pid, rev);
2926 		len = strlen(p) + 1;
2927 		p += len;
2928 		tlen -= len;
2929 	}
2930 
2931 	/* ( 5) scsiclass,DDEEFFF.vV.pP */
2932 	if ((dtype_device != dtype_node) && *gf && *vid && *pid) {
2933 		*csp++ = p;
2934 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s",
2935 		    dtype_node, dtype_device, gf, vid, pid);
2936 		len = strlen(p) + 1;
2937 		p += len;
2938 		tlen -= len;
2939 	}
2940 
2941 	/* ( 6) scsiclass,DDEE.vV.pP */
2942 	if ((dtype_device != dtype_node) && *vid && *pid) {
2943 		*csp++ = p;
2944 		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s",
2945 		    dtype_node, dtype_device, vid, pid);
2946 		len = strlen(p) + 1;
2947 		p += len;
2948 		tlen -= len;
2949 	}
2950 
2951 	/* ( 7) scsiclass,DDFFF.vV.pP */
2952 	if (*gf && *vid && *pid) {
2953 		*csp++ = p;
2954 		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s",
2955 		    dtype_node, gf, vid, pid);
2956 		len = strlen(p) + 1;
2957 		p += len;
2958 		tlen -= len;
2959 	}
2960 
2961 	/* ( 8) scsiclass,DD.vV.pP */
2962 	if (*vid && *pid) {
2963 		*csp++ = p;
2964 		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s",
2965 		    dtype_node, vid, pid);
2966 		len = strlen(p) + 1;
2967 		p += len;
2968 		tlen -= len;
2969 	}
2970 
2971 	/* (8.5) scsa,DD.bB (not documented in scsi(4)) */
2972 	if (binding_set) {
2973 		*csp++ = p;
2974 		(void) snprintf(p, tlen, "scsa,%02x.b%s",
2975 		    dtype_node, binding_set);
2976 		len = strlen(p) + 1;
2977 		p += len;
2978 		tlen -= len;
2979 	}
2980 
2981 	/* ( 9) scsiclass,DDEEFFF */
2982 	if ((dtype_device != dtype_node) && *gf) {
2983 		*csp++ = p;
2984 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s",
2985 		    dtype_node, dtype_device, gf);
2986 		len = strlen(p) + 1;
2987 		p += len;
2988 		tlen -= len;
2989 	}
2990 
2991 	/* (10) scsiclass,DDEE */
2992 	if (dtype_device != dtype_node) {
2993 		*csp++ = p;
2994 		(void) snprintf(p, tlen, "scsiclass,%02x%02x",
2995 		    dtype_node, dtype_device);
2996 		len = strlen(p) + 1;
2997 		p += len;
2998 		tlen -= len;
2999 	}
3000 
3001 	/* (11) scsiclass,DDFFF */
3002 	if (*gf) {
3003 		*csp++ = p;
3004 		(void) snprintf(p, tlen, "scsiclass,%02x%s",
3005 		    dtype_node, gf);
3006 		len = strlen(p) + 1;
3007 		p += len;
3008 		tlen -= len;
3009 	}
3010 
3011 	/* (12) scsiclass,DD */
3012 	*csp++ = p;
3013 	(void) snprintf(p, tlen, "scsiclass,%02x", dtype_node);
3014 	len = strlen(p) + 1;
3015 	p += len;
3016 	tlen -= len;
3017 
3018 	/* (12.5) scsa.fFFF */
3019 	if (*ff) {
3020 		*csp++ = p;
3021 		(void) snprintf(p, tlen, "scsa.f%s", ff);
3022 		len = strlen(p) + 1;
3023 		p += len;
3024 		tlen -= len;
3025 	}
3026 
3027 	/* (13) scsiclass */
3028 	*csp++ = p;
3029 	(void) snprintf(p, tlen, "scsiclass");
3030 	len = strlen(p) + 1;
3031 	p += len;
3032 	tlen -= len;
3033 	ASSERT(tlen >= 0);
3034 
3035 	*csp = NULL;			/* NULL terminate array of pointers */
3036 	ncompat = csp - compatp;
3037 
3038 	/*
3039 	 * When determining a nodename, a nodename_aliases specified
3040 	 * mapping has precedence over using a driver_aliases specified
3041 	 * driver binding as a nodename.
3042 	 *
3043 	 * See if any of the compatible forms have a nodename_aliases
3044 	 * specified nodename. These mappings are described by
3045 	 * nodename_aliases entries like:
3046 	 *
3047 	 *	disk		"scsiclass,00"
3048 	 *	enclosure	"scsiclass,03.vSYMBIOS.pD1000"
3049 	 *	ssd		"scsa,00.bfcp"
3050 	 *
3051 	 * All nodename_aliases mappings should idealy be to generic
3052 	 * names, however a higher precedence legacy mapping to a
3053 	 * driver name may exist. The highest precedence mapping
3054 	 * provides the nodename, so legacy driver nodename mappings
3055 	 * (if they exist) take precedence over generic nodename
3056 	 * mappings.
3057 	 */
3058 	for (nname = NULL, csp = compatp; (nname == NULL) && *csp; csp++) {
3059 		for (nap = na; nap->na_nodename; nap++) {
3060 			if (strcmp(*csp, nap->na_alias) == 0) {
3061 				nname = nap->na_nodename;
3062 				break;
3063 			}
3064 		}
3065 	}
3066 
3067 	/*
3068 	 * If no nodename_aliases mapping exists then use the
3069 	 * driver_aliases specified driver binding as a nodename.
3070 	 * Determine the driver based on compatible (which may
3071 	 * have the passed in compat0 as the first item). The
3072 	 * driver_aliases file has entries like
3073 	 *
3074 	 *	sd	"scsiclass,00"
3075 	 *
3076 	 * that map compatible forms to specific drivers. These
3077 	 * entries are established by add_drv. We use the most specific
3078 	 * driver binding as the nodename. This matches the eventual
3079 	 * ddi_driver_compatible_major() binding that will be
3080 	 * established by bind_node()
3081 	 */
3082 	if (nname == NULL) {
3083 		for (dname = NULL, csp = compatp; *csp; csp++) {
3084 			major = ddi_name_to_major(*csp);
3085 			if ((major == (major_t)-1) ||
3086 			    (devnamesp[major].dn_flags & DN_DRIVER_REMOVED))
3087 				continue;
3088 			if (dname = ddi_major_to_name(major))
3089 				break;
3090 		}
3091 		nname = dname;
3092 	}
3093 
3094 	/* return results */
3095 	if (nname) {
3096 		*nodenamep = kmem_alloc(strlen(nname) + 1, KM_SLEEP);
3097 		(void) strcpy(*nodenamep, nname);
3098 	} else {
3099 		*nodenamep = NULL;
3100 
3101 		/*
3102 		 * If no nodename could be determined return a special
3103 		 * 'compatible' to be used for a diagnostic message. This
3104 		 * compatible contains all compatible forms concatenated
3105 		 * into a single string pointed to by the first element.
3106 		 */
3107 		if (nname == NULL) {
3108 			for (csp = compatp; *(csp + 1); csp++)
3109 				*((*csp) + strlen(*csp)) = ' ';
3110 			*(compatp + 1) = NULL;
3111 			ncompat = 1;
3112 		}
3113 
3114 	}
3115 	*compatiblep = compatp;
3116 	*ncompatiblep = ncompat;
3117 }
3118 
3119 void
3120 scsi_hba_nodename_compatible_get(struct scsi_inquiry *inq,
3121     char *binding_set, int dtype_node, char *compat0,
3122     char **nodenamep, char ***compatiblep, int *ncompatiblep)
3123 {
3124 	scsi_hba_identity_nodename_compatible_get(inq,
3125 	    NULL, 0, NULL, 0, binding_set, dtype_node, compat0, nodenamep,
3126 	    compatiblep, ncompatiblep);
3127 }
3128 
3129 /*
3130  * Free allocations associated with scsi_hba_nodename_compatible_get or
3131  * scsi_hba_identity_nodename_compatible_get use.
3132  */
3133 void
3134 scsi_hba_nodename_compatible_free(char *nodename, char **compatible)
3135 {
3136 	if (nodename)
3137 		kmem_free(nodename, strlen(nodename) + 1);
3138 
3139 	if (compatible)
3140 		kmem_free(compatible, (NCOMPAT * sizeof (char *)) +
3141 		    (NCOMPAT * COMPAT_LONGEST));
3142 }
3143 
3144 static int
3145 scsi_hba_bus_config(dev_info_t *self, uint_t flag, ddi_bus_config_op_t op,
3146     void *arg, dev_info_t **childp)
3147 {
3148 	scsi_hba_tran_t	*tran;
3149 
3150 	tran = ddi_get_driver_private(self);
3151 	if (tran && tran->tran_bus_config) {
3152 		return (tran->tran_bus_config(self, flag, op, arg, childp));
3153 	}
3154 
3155 	/*
3156 	 * Force reprobe for BUS_CONFIG_ONE or when manually reconfiguring
3157 	 * via devfsadm(1m) to emulate deferred attach.
3158 	 * Reprobe only discovers driver.conf enumerated nodes, more
3159 	 * dynamic implementations probably require their own bus_config.
3160 	 */
3161 	if ((op == BUS_CONFIG_ONE) || (flag & NDI_DRV_CONF_REPROBE))
3162 		flag |= NDI_CONFIG_REPROBE;
3163 
3164 	return (ndi_busop_bus_config(self, flag, op, arg, childp, 0));
3165 }
3166 
3167 static int
3168 scsi_hba_bus_unconfig(dev_info_t *self, uint_t flag, ddi_bus_config_op_t op,
3169     void *arg)
3170 {
3171 	scsi_hba_tran_t	*tran;
3172 
3173 	tran = ddi_get_driver_private(self);
3174 	if (tran && tran->tran_bus_unconfig) {
3175 		return (tran->tran_bus_unconfig(self, flag, op, arg));
3176 	}
3177 	return (ndi_busop_bus_unconfig(self, flag, op, arg));
3178 }
3179 
3180 void
3181 scsi_hba_pkt_comp(struct scsi_pkt *pkt)
3182 {
3183 	ASSERT(pkt);
3184 	if (pkt->pkt_comp == NULL)
3185 		return;
3186 
3187 	/*
3188 	 * For HBA drivers that implement tran_setup_pkt(9E), if we are
3189 	 * completing a 'consistent' mode DMA operation then we must
3190 	 * perform dma_sync prior to calling pkt_comp to ensure that
3191 	 * the target driver sees the correct data in memory.
3192 	 */
3193 	ASSERT((pkt->pkt_flags & FLAG_NOINTR) == 0);
3194 	if (((pkt->pkt_dma_flags & DDI_DMA_CONSISTENT) &&
3195 	    (pkt->pkt_dma_flags & DDI_DMA_READ)) &&
3196 	    ((P_TO_TRAN(pkt)->tran_setup_pkt) != NULL)) {
3197 		scsi_sync_pkt(pkt);
3198 	}
3199 	(*pkt->pkt_comp)(pkt);
3200 }
3201