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