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