xref: /illumos-gate/usr/src/uts/common/io/scsi/impl/scsi_hba.c (revision 5f8171005a0c33f3c67f7da52d41c2362c3fd891)
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/scsi/generic/sas.h>
33 #include <sys/file.h>
34 #include <sys/disp.h>			/* for minclsyspri */
35 #include <sys/ddi_impldefs.h>
36 #include <sys/ndi_impldefs.h>
37 #include <sys/sunndi.h>
38 #include <sys/ddi.h>
39 #include <sys/sunmdi.h>
40 #include <sys/mdi_impldefs.h>
41 #include <sys/callb.h>
42 #include <sys/epm.h>
43 #include <sys/damap.h>
44 #include <sys/time.h>
45 #include <sys/sunldi.h>
46 
47 extern struct scsi_pkt *scsi_init_cache_pkt(struct scsi_address *,
48 		    struct scsi_pkt *, struct buf *, int, int, int, int,
49 		    int (*)(caddr_t), caddr_t);
50 extern void	scsi_free_cache_pkt(struct scsi_address *, struct scsi_pkt *);
51 extern void	scsi_cache_dmafree(struct scsi_address *, struct scsi_pkt *);
52 extern void	scsi_sync_cache_pkt(struct scsi_address *, struct scsi_pkt *);
53 extern int	modrootloaded;
54 
55 /*
56  * Round up all allocations so that we can guarantee
57  * long-long alignment.  This is the same alignment
58  * provided by kmem_alloc().
59  */
60 #define	ROUNDUP(x)	(((x) + 0x07) & ~0x07)
61 
62 /* Magic number to track correct allocations in wrappers */
63 #define	PKT_WRAPPER_MAGIC	0xa110ced	/* alloced correctly */
64 
65 kmutex_t	scsi_flag_nointr_mutex;
66 kcondvar_t	scsi_flag_nointr_cv;
67 kmutex_t	scsi_log_mutex;
68 
69 /* asynchronous probe barrier deletion data structures */
70 static kmutex_t	scsi_hba_barrier_mutex;
71 static kcondvar_t	scsi_hba_barrier_cv;
72 static struct scsi_hba_barrier {
73 	struct scsi_hba_barrier	*barrier_next;
74 	clock_t			barrier_endtime;
75 	dev_info_t		*barrier_probe;
76 }		*scsi_hba_barrier_list;
77 static int	scsi_hba_devi_is_barrier(dev_info_t *probe);
78 static void	scsi_hba_barrier_tran_tgt_free(dev_info_t *probe);
79 static void	scsi_hba_barrier_add(dev_info_t *probe, int seconds);
80 static int	scsi_hba_remove_node(dev_info_t *child);
81 static void	scsi_hba_barrier_daemon(void *arg);
82 
83 /* LUN-change ASC/ASCQ processing data structures (stage1 and stage2) */
84 static kmutex_t		scsi_lunchg1_mutex;
85 static kcondvar_t	scsi_lunchg1_cv;
86 static struct scsi_pkt	*scsi_lunchg1_list;
87 static void		scsi_lunchg1_daemon(void *arg);
88 static kmutex_t		scsi_lunchg2_mutex;
89 static kcondvar_t	scsi_lunchg2_cv;
90 static struct scsi_lunchg2 {
91 	struct scsi_lunchg2	*lunchg2_next;
92 	char			*lunchg2_path;
93 }			*scsi_lunchg2_list;
94 static void		scsi_lunchg2_daemon(void *arg);
95 
96 static int	scsi_hba_find_child(dev_info_t *self, char *name, char *addr,
97     int init, dev_info_t **dchildp, mdi_pathinfo_t **pchildp, int *ppi);
98 
99 /* return value defines for scsi_hba_find_child */
100 #define	CHILD_TYPE_NONE		0
101 #define	CHILD_TYPE_DEVINFO	1
102 #define	CHILD_TYPE_PATHINFO	2
103 
104 /*
105  * Enumeration code path currently being followed. SE_BUSCONFIG results in
106  * DEVI_SID_NODEID, and SE_HP (hotplug) results in DEVI_SID_HP_NODEID.
107  *
108  * Since hotplug enumeration is based on information obtained from hardware
109  * (tgtmap/report_lun) the type/severity of enumeration error messages is
110  * sometimes based SE_HP (indirectly via ndi_dev_is_hotplug_node()). By
111  * convention, these messages all contain "enumeration failed during ...".
112  */
113 typedef enum { SE_BUSCONFIG = 0, SE_HP = 1 } scsi_enum_t;
114 
115 /* compatible properties of driver to use during probe/enumeration operations */
116 static char	*compatible_probe = "scsa,probe";
117 static char	*compatible_nodev = "scsa,nodev";
118 static char	*scsi_probe_ascii[] = SCSIPROBE_ASCII;
119 
120 /* number of LUNs we attempt to get on the first SCMD_REPORT_LUNS command */
121 int	scsi_lunrpt_default_max = 256;
122 int	scsi_lunrpt_timeout = 3;	/* seconds */
123 
124 /* 'scsi-binding-set' value for legacy enumerated 'spi' transports */
125 char	*scsi_binding_set_spi = "spi";
126 
127 /* enable NDI_DEVI_DEBUG for bus_[un]config operations */
128 int	scsi_hba_busconfig_debug = 0;
129 
130 /* number of probe serilization messages */
131 int	scsi_hba_wait_msg = 5;
132 
133 /*
134  * Establish the timeout used to cache (in the probe node) the fact that the
135  * device does not exist. This replaces the target specific probe cache.
136  */
137 int	scsi_hba_barrier_timeout = (60);		/* seconds */
138 
139 /*
140  * Structure for scsi_hba_tgtmap_* implementation.
141  *
142  * Every call to scsi_hba_tgtmap_set_begin will increment tgtmap_reports,
143  * and a call to scsi_hba_tgtmap_set_end will reset tgtmap_reports to zero.
144  * If, in scsi_hba_tgtmap_set_begin, we detect a tgtmap_reports value of
145  * scsi_hba_tgtmap_reports_max we produce a message to indicate that
146  * the caller is never completing an observation (i.e. we are not making
147  * any forward progress). If this message occurs, it indicates that the
148  * solaris hotplug ramifications at the target and lun level are no longer
149  * tracking.
150  *
151  * NOTE: LUNMAPSIZE OK for now, but should be dynamic in reportlun code.
152  */
153 typedef struct impl_scsi_tgtmap {
154 	scsi_hba_tran_t *tgtmap_tran;
155 	int		tgtmap_reports;		/* _begin without _end */
156 	int		tgtmap_noisy;
157 	scsi_tgt_activate_cb_t tgtmap_activate_cb;
158 	scsi_tgt_deactivate_cb_t tgtmap_deactivate_cb;
159 	void		*tgtmap_mappriv;
160 	damap_t		*tgtmap_dam[SCSI_TGT_NTYPES];
161 } impl_scsi_tgtmap_t;
162 #define	LUNMAPSIZE 256		/* 256 LUNs/target */
163 
164 /* Produce warning if number of begins without an end exceed this value */
165 int	scsi_hba_tgtmap_reports_max = 256;
166 
167 /* Prototype for static dev_ops devo_*() functions */
168 static int	scsi_hba_info(
169 			dev_info_t		*self,
170 			ddi_info_cmd_t		infocmd,
171 			void			*arg,
172 			void			**result);
173 
174 /* Prototypes for static bus_ops bus_*() functions */
175 static int	scsi_hba_bus_ctl(
176 			dev_info_t		*self,
177 			dev_info_t		*child,
178 			ddi_ctl_enum_t		op,
179 			void			*arg,
180 			void			*result);
181 
182 static int	scsi_hba_map_fault(
183 			dev_info_t		*self,
184 			dev_info_t		*child,
185 			struct hat		*hat,
186 			struct seg		*seg,
187 			caddr_t			addr,
188 			struct devpage		*dp,
189 			pfn_t			pfn,
190 			uint_t			prot,
191 			uint_t			lock);
192 
193 static int	scsi_hba_get_eventcookie(
194 			dev_info_t		*self,
195 			dev_info_t		*child,
196 			char			*name,
197 			ddi_eventcookie_t	*eventp);
198 
199 static int	scsi_hba_add_eventcall(
200 			dev_info_t		*self,
201 			dev_info_t		*child,
202 			ddi_eventcookie_t	event,
203 			void			(*callback)(
204 				dev_info_t		*dip,
205 				ddi_eventcookie_t	event,
206 				void			*arg,
207 				void			*bus_impldata),
208 			void			*arg,
209 			ddi_callback_id_t	*cb_id);
210 
211 static int	scsi_hba_remove_eventcall(
212 			dev_info_t		*self,
213 			ddi_callback_id_t	id);
214 
215 static int	scsi_hba_post_event(
216 			dev_info_t		*self,
217 			dev_info_t		*child,
218 			ddi_eventcookie_t	event,
219 			void			*bus_impldata);
220 
221 static int	scsi_hba_bus_config(
222 			dev_info_t		*self,
223 			uint_t			flags,
224 			ddi_bus_config_op_t	op,
225 			void			*arg,
226 			dev_info_t		**childp);
227 
228 static int	scsi_hba_bus_unconfig(
229 			dev_info_t		*self,
230 			uint_t			flags,
231 			ddi_bus_config_op_t	op,
232 			void			*arg);
233 
234 static int	scsi_hba_fm_init_child(
235 			dev_info_t		*self,
236 			dev_info_t		*child,
237 			int			cap,
238 			ddi_iblock_cookie_t	*ibc);
239 
240 static int	scsi_hba_bus_power(
241 			dev_info_t		*self,
242 			void			*impl_arg,
243 			pm_bus_power_op_t	op,
244 			void			*arg,
245 			void			*result);
246 
247 /* bus_ops vector for SCSI HBA's. */
248 static struct bus_ops scsi_hba_busops = {
249 	BUSO_REV,
250 	nullbusmap,			/* bus_map */
251 	NULL,				/* bus_get_intrspec */
252 	NULL,				/* bus_add_intrspec */
253 	NULL,				/* bus_remove_intrspec */
254 	scsi_hba_map_fault,		/* bus_map_fault */
255 	ddi_dma_map,			/* bus_dma_map */
256 	ddi_dma_allochdl,		/* bus_dma_allochdl */
257 	ddi_dma_freehdl,		/* bus_dma_freehdl */
258 	ddi_dma_bindhdl,		/* bus_dma_bindhdl */
259 	ddi_dma_unbindhdl,		/* bus_unbindhdl */
260 	ddi_dma_flush,			/* bus_dma_flush */
261 	ddi_dma_win,			/* bus_dma_win */
262 	ddi_dma_mctl,			/* bus_dma_ctl */
263 	scsi_hba_bus_ctl,		/* bus_ctl */
264 	ddi_bus_prop_op,		/* bus_prop_op */
265 	scsi_hba_get_eventcookie,	/* bus_get_eventcookie */
266 	scsi_hba_add_eventcall,		/* bus_add_eventcall */
267 	scsi_hba_remove_eventcall,	/* bus_remove_eventcall */
268 	scsi_hba_post_event,		/* bus_post_event */
269 	NULL,				/* bus_intr_ctl */
270 	scsi_hba_bus_config,		/* bus_config */
271 	scsi_hba_bus_unconfig,		/* bus_unconfig */
272 	scsi_hba_fm_init_child,		/* bus_fm_init */
273 	NULL,				/* bus_fm_fini */
274 	NULL,				/* bus_fm_access_enter */
275 	NULL,				/* bus_fm_access_exit */
276 	scsi_hba_bus_power		/* bus_power */
277 };
278 
279 /* cb_ops for hotplug :devctl and :scsi support */
280 static struct cb_ops scsi_hba_cbops = {
281 	scsi_hba_open,
282 	scsi_hba_close,
283 	nodev,			/* strategy */
284 	nodev,			/* print */
285 	nodev,			/* dump */
286 	nodev,			/* read */
287 	nodev,			/* write */
288 	scsi_hba_ioctl,		/* ioctl */
289 	nodev,			/* devmap */
290 	nodev,			/* mmap */
291 	nodev,			/* segmap */
292 	nochpoll,		/* poll */
293 	ddi_prop_op,		/* prop_op */
294 	NULL,			/* stream */
295 	D_NEW|D_MP|D_HOTPLUG,	/* cb_flag */
296 	CB_REV,			/* rev */
297 	nodev,			/* int (*cb_aread)() */
298 	nodev			/* int (*cb_awrite)() */
299 };
300 
301 /* Prototypes for static scsi_hba.c/SCSA private lunmap interfaces */
302 static int	scsi_lunmap_create(
303 			dev_info_t		*self,
304 			impl_scsi_tgtmap_t	*tgtmap,
305 			char			*tgt_addr);
306 static void	scsi_lunmap_destroy(
307 			dev_info_t		*self,
308 			impl_scsi_tgtmap_t	*tgtmap,
309 			char			*tgt_addr);
310 static void	scsi_lunmap_set_begin(
311 			dev_info_t		*self,
312 			damap_t			*lundam);
313 static int	scsi_lunmap_set_add(
314 			dev_info_t		*self,
315 			damap_t			*lundam,
316 			char			*taddr,
317 			scsi_lun64_t		lun_num,
318 			int			lun_sfunc);
319 static void	scsi_lunmap_set_end(
320 			dev_info_t		*self,
321 			damap_t			*lundam);
322 
323 /* Prototypes for static misc. scsi_hba.c private bus_config interfaces */
324 static int scsi_hba_bus_config_iports(dev_info_t *self, uint_t flags,
325     ddi_bus_config_op_t op, void *arg, dev_info_t **childp);
326 static int scsi_hba_bus_config_spi(dev_info_t *self, uint_t flags,
327     ddi_bus_config_op_t op, void *arg, dev_info_t **childp);
328 static dev_info_t *scsi_hba_bus_config_port(dev_info_t *self,
329     char *nameaddr, scsi_enum_t se);
330 
331 #ifdef	sparc
332 static int scsi_hba_bus_config_prom_node(dev_info_t *self, uint_t flags,
333     void *arg, dev_info_t **childp);
334 #endif	/* sparc */
335 
336 
337 /*
338  * SCSI_HBA_LOG is used for all messages. A logging level is specified when
339  * generating a message. Some levels correspond directly to cmn_err levels,
340  * some are associated with increasing levels diagnostic/debug output (LOG1-4),
341  * and others are associated with specific levels of interface (LOGMAP).
342  * For _LOG() messages, a __func__ prefix will identify the function origin
343  * of the message. For _LOG_NF messages, there is no function prefix or
344  * self/child context. Filtering of messages is provided based on logging
345  * level, but messages with cmn_err logging level and messages generated
346  * generated with _LOG_NF() are never filtered.
347  *
348  * For debugging, more complete information can be displayed with each message
349  * (full device path and pointer values) by adjusting scsi_hba_log_info.
350  */
351 /* logging levels */
352 #define	SCSI_HBA_LOGCONT	CE_CONT
353 #define	SCSI_HBA_LOGNOTE	CE_NOTE
354 #define	SCSI_HBA_LOGWARN	CE_WARN
355 #define	SCSI_HBA_LOGPANIC	CE_PANIC
356 #define	SCSI_HBA_LOGIGNORE	CE_IGNORE
357 #define	SCSI_HBA_LOG_CE_MASK	0x0000000F	/* no filter for these levels */
358 #define	SCSI_HBA_LOG1		0x00000010	/* DIAG1 level enable */
359 #define	SCSI_HBA_LOG2		0x00000020	/* DIAG2 level enable */
360 #define	SCSI_HBA_LOG3		0x00000040	/* DIAG3 level enable */
361 #define	SCSI_HBA_LOG4		0x00000080	/* DIAG4 level enable */
362 #define	SCSI_HBA_LOGMAPPHY	0x00000100	/* MAPPHY level enable */
363 #define	SCSI_HBA_LOGMAPIPT	0x00000200	/* MAPIPT level enable */
364 #define	SCSI_HBA_LOGMAPTGT	0x00000400	/* MAPTGT level enable */
365 #define	SCSI_HBA_LOGMAPLUN	0x00000800	/* MAPLUN level enable */
366 #define	SCSI_HBA_LOGMAPCFG	0x00001000	/* MAPCFG level enable */
367 #define	SCSI_HBA_LOGMAPUNCFG	0x00002000	/* MAPUNCFG level enable */
368 #define	SCSI_HBA_LOGTRACE	0x00010000	/* TRACE enable */
369 #if (CE_CONT | CE_NOTE | CE_WARN | CE_PANIC | CE_IGNORE) > SCSI_HBA_LOG_CE_MASK
370 Error, problem with CE_ definitions
371 #endif
372 
373 /*
374  * Tunable log message augmentation and filters: filters do not apply to
375  * SCSI_HBA_LOG_CE_MASK level messages or LOG_NF() messages.
376  *
377  * An example set of /etc/system tunings to simplify debug a SCSA pHCI HBA
378  * driver called "pmcs", including "scsi_vhci" operation, by capturing
379  * log information in the system log might be:
380  *
381  * echo "set scsi:scsi_hba_log_filter_level=0x3ff0"		>> /etc/system
382  * echo "set scsi:scsi_hba_log_filter_phci=\"pmcs\""		>> /etc/system
383  * echo "set scsi:scsi_hba_log_filter_vhci=\"scsi_vhci\""	>> /etc/system
384  *
385  * To capture information on just HBA-SCSAv3 *map operation, use
386  * echo "set scsi:scsi_hba_log_filter_level=0x3f10"		>> /etc/system
387  *
388  * For debugging an HBA driver, you may also want to set:
389  *
390  * echo "set scsi:scsi_hba_log_align=1"				>> /etc/system
391  * echo "set scsi:scsi_hba_log_mt_disable=0x6"			>> /etc/system
392  * echo "set mtc_off=1"						>> /etc/system
393  * echo "set mdi_mtc_off=1"					>> /etc/system
394  * echo "set scsi:scsi_hba_log_fcif=0"				>> /etc/system
395  */
396 int		scsi_hba_log_filter_level =
397 			SCSI_HBA_LOG1 |
398 			0;
399 char		*scsi_hba_log_filter_phci = "\0\0\0\0\0\0\0\0\0\0\0\0";
400 char		*scsi_hba_log_filter_vhci = "\0\0\0\0\0\0\0\0\0\0\0\0";
401 int		scsi_hba_log_align = 0;	/* NOTE: will not cause truncation */
402 int		scsi_hba_log_fcif = '!'; /* "^!?" first char in format */
403 					/* NOTE: iff level > SCSI_HBA_LOG1 */
404 					/* '\0'0x00 -> console and system log */
405 					/* '^' 0x5e -> console_only */
406 					/* '!' 0x21 -> system log only */
407 					/* '?' 0x2F -> See cmn_err(9F) */
408 int		scsi_hba_log_info =	/* augmentation: extra info output */
409 			(0 << 0) |	/* 0x0001: process information */
410 			(0 << 1) |	/* 0x0002: full /devices path */
411 			(0 << 2);	/* 0x0004: devinfo pointer */
412 
413 int		scsi_hba_log_mt_disable =
414 			/* SCSI_ENUMERATION_MT_LUN_DISABLE |	(ie 0x02) */
415 			/* SCSI_ENUMERATION_MT_TARGET_DISABLE |	(ie 0x04) */
416 			0;
417 
418 /* static data for HBA logging subsystem */
419 static kmutex_t	scsi_hba_log_mutex;
420 static char	scsi_hba_log_i[512];
421 static char	scsi_hba_log_buf[512];
422 static char	scsi_hba_fmt[512];
423 
424 /* Macros to use in scsi_hba.c source code below */
425 #define	SCSI_HBA_LOG(x)	scsi_hba_log x
426 #define	_LOG(level)	SCSI_HBA_LOG##level, __func__
427 #define	_MAP(map)	SCSI_HBA_LOGMAP##map, __func__
428 #define	_LOG_NF(level)	SCSI_HBA_LOG##level, NULL, NULL, NULL
429 #define	_LOG_TRACE	_LOG(TRACE)
430 #define	_LOGLUN		_MAP(LUN)
431 #define	_LOGTGT		_MAP(TGT)
432 #define	_LOGIPT		_MAP(IPT)
433 #define	_LOGPHY		_MAP(PHY)
434 #define	_LOGCFG		_MAP(CFG)
435 #define	_LOGUNCFG	_MAP(UNCFG)
436 
437 /*PRINTFLIKE5*/
438 static void
439 scsi_hba_log(int level, const char *func, dev_info_t *self, dev_info_t *child,
440     const char *fmt, ...)
441 {
442 	va_list		ap;
443 	int		clevel;
444 	int		align;
445 	char		*info;
446 	char		*f;
447 	char		*ua;
448 
449 	/* derive self from child's parent */
450 	if ((self == NULL) && child)
451 		self = ddi_get_parent(child);
452 
453 	/* no filtering of SCSI_HBA_LOG_CE_MASK or LOG_NF messages */
454 	if (((level & SCSI_HBA_LOG_CE_MASK) != level) && (func != NULL)) {
455 		/* scsi_hba_log_filter_level: filter on level as bitmask */
456 		if ((level & scsi_hba_log_filter_level) == 0)
457 			return;
458 
459 		/* scsi_hba_log_filter_phci/vhci: on name of driver */
460 		if (*scsi_hba_log_filter_phci &&
461 		    ((self == NULL) ||
462 		    (ddi_driver_name(self) == NULL) ||
463 		    strcmp(ddi_driver_name(self), scsi_hba_log_filter_phci))) {
464 			/* does not match pHCI, check vHCI */
465 			if (*scsi_hba_log_filter_vhci &&
466 			    ((self == NULL) ||
467 			    (ddi_driver_name(self) == NULL) ||
468 			    strcmp(ddi_driver_name(self),
469 			    scsi_hba_log_filter_vhci))) {
470 				/* does not match vHCI */
471 				return;
472 			}
473 		}
474 
475 
476 		/* passed filters, determine align */
477 		align = scsi_hba_log_align;
478 
479 		/* shorten func for filtered output */
480 		if (strncmp(func, "scsi_hba_", 9) == 0)
481 			func += 9;
482 		if (strncmp(func, "scsi_", 5) == 0)
483 			func += 5;
484 	} else {
485 		/* don't align output that is never filtered */
486 		align = 0;
487 	}
488 
489 	/* determine the cmn_err form from the level */
490 	clevel = ((level & SCSI_HBA_LOG_CE_MASK) == level) ? level : CE_CONT;
491 
492 	/* protect common buffers used to format output */
493 	mutex_enter(&scsi_hba_log_mutex);
494 
495 	/* skip special first characters, we add them back below */
496 	f = (char *)fmt;
497 	if (*f && strchr("^!?", *f))
498 		f++;
499 	va_start(ap, fmt);
500 	(void) vsprintf(scsi_hba_log_buf, f, ap);
501 	va_end(ap);
502 
503 	/* augment message with 'information' */
504 	info = scsi_hba_log_i;
505 	*info = '\0';
506 	if ((scsi_hba_log_info & 0x0001) && curproc && PTOU(curproc)->u_comm) {
507 		(void) sprintf(info, "%s[%d]%p ",
508 		    PTOU(curproc)->u_comm, curproc->p_pid, (void *)curthread);
509 		info += strlen(info);
510 	}
511 	if (self) {
512 		if ((scsi_hba_log_info & 0x0004) && (child || self)) {
513 			(void) sprintf(info, "%p ",
514 			    (void *)(child ? child : self));
515 			info += strlen(info);
516 		}
517 		if (scsi_hba_log_info & 0x0002)	{
518 			(void) ddi_pathname(child ? child : self, info);
519 			(void) strcat(info, " ");
520 			info += strlen(info);
521 		}
522 
523 		/* always provide 'default' information about self &child */
524 		(void) sprintf(info, "%s%d ", ddi_driver_name(self),
525 		    ddi_get_instance(self));
526 		info += strlen(info);
527 		if (child) {
528 			ua = ddi_get_name_addr(child);
529 			(void) sprintf(info, "%s@%s ",
530 			    ddi_node_name(child), (ua && *ua) ? ua : "");
531 			info += strlen(info);
532 		}
533 	}
534 
535 	/* turn off alignment if truncation would occur */
536 	if (align && ((strlen(func) > 18) || (strlen(scsi_hba_log_i) > 36)))
537 		align = 0;
538 
539 	/* adjust for aligned output */
540 	if (align) {
541 		if (func == NULL)
542 			func = "";
543 		/* remove trailing blank with align output */
544 		if ((info != scsi_hba_log_i) && (*(info -1) == '\b'))
545 			*(info - 1) = '\0';
546 	}
547 
548 	/* special "first character in format" must be in format itself */
549 	f = scsi_hba_fmt;
550 	if (fmt[0] && strchr("^!?", fmt[0]))
551 		*f++ = fmt[0];
552 	else if (scsi_hba_log_fcif && (level > SCSI_HBA_LOG1))
553 		*f++ = (char)scsi_hba_log_fcif;		/* add global fcif */
554 	if (align)
555 		(void) sprintf(f, "%s", "%-18.18s: %36.36s: %s%s");
556 	else
557 		(void) sprintf(f, "%s", func ? "%s: %s%s%s" : "%s%s%s");
558 
559 	if (func)
560 		cmn_err(clevel, scsi_hba_fmt, func, scsi_hba_log_i,
561 		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
562 	else
563 		cmn_err(clevel, scsi_hba_fmt, scsi_hba_log_i,
564 		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
565 	mutex_exit(&scsi_hba_log_mutex);
566 }
567 
568 /*
569  * scsi_hba version of [nm]di_devi_enter/[nm]di_devi_exit that detects if HBA
570  * is a PHCI, and chooses mdi/ndi locking implementation.
571  */
572 static void
573 scsi_hba_devi_enter(dev_info_t *self, int *circp)
574 {
575 	if (MDI_PHCI(self))
576 		mdi_devi_enter(self, circp);
577 	else
578 		ndi_devi_enter(self, circp);
579 }
580 
581 static int
582 scsi_hba_devi_tryenter(dev_info_t *self, int *circp)
583 {
584 	if (MDI_PHCI(self))
585 		return (mdi_devi_tryenter(self, circp));
586 	else
587 		return (ndi_devi_tryenter(self, circp));
588 }
589 
590 static void
591 scsi_hba_devi_exit(dev_info_t *self, int circ)
592 {
593 	if (MDI_PHCI(self))
594 		mdi_devi_exit(self, circ);
595 	else
596 		ndi_devi_exit(self, circ);
597 }
598 
599 static void
600 scsi_hba_devi_enter_phci(dev_info_t *self, int *circp)
601 {
602 	if (MDI_PHCI(self))
603 		mdi_devi_enter_phci(self, circp);
604 }
605 
606 static void
607 scsi_hba_devi_exit_phci(dev_info_t *self, int circ)
608 {
609 	if (MDI_PHCI(self))
610 		mdi_devi_exit_phci(self, circ);
611 }
612 
613 static int
614 scsi_hba_dev_is_sid(dev_info_t *child)
615 {
616 	/*
617 	 * Use ndi_dev_is_persistent_node instead of ddi_dev_is_sid to avoid
618 	 * any possible locking issues in mixed nexus devctl code (like usb).
619 	 */
620 	return (ndi_dev_is_persistent_node(child));
621 }
622 
623 /*
624  * Called from _init() when loading "scsi" module
625  */
626 void
627 scsi_initialize_hba_interface()
628 {
629 	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
630 
631 	/* We need "scsiprobe" and "scsinodev" as an alias or a driver. */
632 	if (ddi_name_to_major(compatible_probe) == DDI_MAJOR_T_NONE) {
633 		SCSI_HBA_LOG((_LOG_NF(WARN), "failed to resolve '%s' "
634 		    "driver alias, defaulting to 'nulldriver'",
635 		    compatible_probe));
636 
637 		/* If no "nulldriver" driver nothing will work... */
638 		compatible_probe = "nulldriver";
639 		if (ddi_name_to_major(compatible_probe) == DDI_MAJOR_T_NONE)
640 			SCSI_HBA_LOG((_LOG_NF(WARN), "no probe '%s' driver, "
641 			    "system misconfigured", compatible_probe));
642 	}
643 	if (ddi_name_to_major(compatible_nodev) == DDI_MAJOR_T_NONE) {
644 		SCSI_HBA_LOG((_LOG_NF(WARN), "failed to resolve '%s' "
645 		    "driver alias, defaulting to 'nulldriver'",
646 		    compatible_nodev));
647 
648 		/* If no "nulldriver" driver nothing will work... */
649 		compatible_nodev = "nulldriver";
650 		if (ddi_name_to_major(compatible_nodev) == DDI_MAJOR_T_NONE)
651 			SCSI_HBA_LOG((_LOG_NF(WARN), "no nodev '%s' driver, "
652 			    "system misconfigured", compatible_nodev));
653 	}
654 
655 	/*
656 	 * Verify our special node name "probe" will not be used in other ways.
657 	 * Don't expect things to work if they are.
658 	 */
659 	if (ddi_major_to_name(ddi_name_to_major("probe")))
660 		SCSI_HBA_LOG((_LOG_NF(WARN),
661 		    "driver already using special node name 'probe'"));
662 
663 	mutex_init(&scsi_log_mutex, NULL, MUTEX_DRIVER, NULL);
664 	mutex_init(&scsi_flag_nointr_mutex, NULL, MUTEX_DRIVER, NULL);
665 	cv_init(&scsi_flag_nointr_cv, NULL, CV_DRIVER, NULL);
666 	mutex_init(&scsi_hba_log_mutex, NULL, MUTEX_DRIVER, NULL);
667 
668 	/* initialize the asynchronous barrier deletion daemon */
669 	mutex_init(&scsi_hba_barrier_mutex, NULL, MUTEX_DRIVER, NULL);
670 	cv_init(&scsi_hba_barrier_cv, NULL, CV_DRIVER, NULL);
671 	(void) thread_create(NULL, 0,
672 	    (void (*)())scsi_hba_barrier_daemon, NULL,
673 	    0, &p0, TS_RUN, minclsyspri);
674 
675 	/* initialize lun change ASC/ASCQ processing daemon (stage1 & stage2) */
676 	mutex_init(&scsi_lunchg1_mutex, NULL, MUTEX_DRIVER, NULL);
677 	cv_init(&scsi_lunchg1_cv, NULL, CV_DRIVER, NULL);
678 	(void) thread_create(NULL, 0,
679 	    (void (*)())scsi_lunchg1_daemon, NULL,
680 	    0, &p0, TS_RUN, minclsyspri);
681 	mutex_init(&scsi_lunchg2_mutex, NULL, MUTEX_DRIVER, NULL);
682 	cv_init(&scsi_lunchg2_cv, NULL, CV_DRIVER, NULL);
683 	(void) thread_create(NULL, 0,
684 	    (void (*)())scsi_lunchg2_daemon, NULL,
685 	    0, &p0, TS_RUN, minclsyspri);
686 }
687 
688 int
689 scsi_hba_pkt_constructor(void *buf, void *arg, int kmflag)
690 {
691 	struct scsi_pkt_cache_wrapper *pktw;
692 	struct scsi_pkt		*pkt;
693 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
694 	int			pkt_len;
695 	char			*ptr;
696 
697 	/*
698 	 * allocate a chunk of memory for the following:
699 	 * scsi_pkt
700 	 * pcw_* fields
701 	 * pkt_ha_private
702 	 * pkt_cdbp, if needed
703 	 * (pkt_private always null)
704 	 * pkt_scbp, if needed
705 	 */
706 	pkt_len = tran->tran_hba_len + sizeof (struct scsi_pkt_cache_wrapper);
707 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB)
708 		pkt_len += DEFAULT_CDBLEN;
709 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
710 		pkt_len += DEFAULT_SCBLEN;
711 	bzero(buf, pkt_len);
712 
713 	ptr = buf;
714 	pktw = buf;
715 	ptr += sizeof (struct scsi_pkt_cache_wrapper);
716 	pkt = &(pktw->pcw_pkt);
717 	pkt->pkt_ha_private = (opaque_t)ptr;
718 
719 	pktw->pcw_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
720 	/*
721 	 * keep track of the granularity at the time this handle was
722 	 * allocated
723 	 */
724 	pktw->pcw_granular = tran->tran_dma_attr.dma_attr_granular;
725 
726 	if (ddi_dma_alloc_handle(tran->tran_hba_dip, &tran->tran_dma_attr,
727 	    kmflag == KM_SLEEP ? SLEEP_FUNC: NULL_FUNC, NULL,
728 	    &pkt->pkt_handle) != DDI_SUCCESS) {
729 
730 		return (-1);
731 	}
732 	ptr += tran->tran_hba_len;
733 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) {
734 		pkt->pkt_cdbp = (opaque_t)ptr;
735 		ptr += DEFAULT_CDBLEN;
736 	}
737 	pkt->pkt_private = NULL;
738 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
739 		pkt->pkt_scbp = (opaque_t)ptr;
740 	if (tran->tran_pkt_constructor)
741 		return ((*tran->tran_pkt_constructor)(pkt, arg, kmflag));
742 	else
743 		return (0);
744 }
745 
746 #define	P_TO_TRAN(pkt)	((pkt)->pkt_address.a_hba_tran)
747 
748 void
749 scsi_hba_pkt_destructor(void *buf, void *arg)
750 {
751 	struct scsi_pkt_cache_wrapper *pktw = buf;
752 	struct scsi_pkt		*pkt = &(pktw->pcw_pkt);
753 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
754 
755 	ASSERT(pktw->pcw_magic == PKT_WRAPPER_MAGIC);
756 	ASSERT((pktw->pcw_flags & PCW_BOUND) == 0);
757 	if (tran->tran_pkt_destructor)
758 		(*tran->tran_pkt_destructor)(pkt, arg);
759 
760 	/* make sure nobody messed with our pointers */
761 	ASSERT(pkt->pkt_ha_private == (opaque_t)((char *)pkt +
762 	    sizeof (struct scsi_pkt_cache_wrapper)));
763 	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_SCB) == 0) ||
764 	    (pkt->pkt_scbp == (opaque_t)((char *)pkt +
765 	    tran->tran_hba_len +
766 	    (((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ?
767 	    0 : DEFAULT_CDBLEN) +
768 	    DEFAULT_PRIVLEN + sizeof (struct scsi_pkt_cache_wrapper))));
769 	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ||
770 	    (pkt->pkt_cdbp == (opaque_t)((char *)pkt +
771 	    tran->tran_hba_len +
772 	    sizeof (struct scsi_pkt_cache_wrapper))));
773 	ASSERT(pkt->pkt_handle);
774 	ddi_dma_free_handle(&pkt->pkt_handle);
775 	pkt->pkt_handle = NULL;
776 	pkt->pkt_numcookies = 0;
777 	pktw->pcw_total_xfer = 0;
778 	pktw->pcw_totalwin = 0;
779 	pktw->pcw_curwin = 0;
780 }
781 
782 /*
783  * Called by an HBA from _init() to plumb in common SCSA bus_ops and
784  * cb_ops for the HBA's :devctl and :scsi minor nodes.
785  */
786 int
787 scsi_hba_init(struct modlinkage *modlp)
788 {
789 	struct dev_ops *hba_dev_ops;
790 
791 	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
792 
793 	/*
794 	 * Get a pointer to the dev_ops structure of the HBA and plumb our
795 	 * bus_ops vector into the HBA's dev_ops structure.
796 	 */
797 	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
798 	ASSERT(hba_dev_ops->devo_bus_ops == NULL);
799 	hba_dev_ops->devo_bus_ops = &scsi_hba_busops;
800 
801 	/*
802 	 * Plumb our cb_ops vector into the HBA's dev_ops structure to
803 	 * provide getinfo and hotplugging ioctl support if the HBA driver
804 	 * does not already provide this support.
805 	 */
806 	if (hba_dev_ops->devo_cb_ops == NULL) {
807 		hba_dev_ops->devo_cb_ops = &scsi_hba_cbops;
808 	}
809 	if (hba_dev_ops->devo_cb_ops->cb_open == scsi_hba_open) {
810 		ASSERT(hba_dev_ops->devo_cb_ops->cb_close == scsi_hba_close);
811 		hba_dev_ops->devo_getinfo = scsi_hba_info;
812 	}
813 	return (0);
814 }
815 
816 /*
817  * Called by an HBA attach(9E) to allocate a scsi_hba_tran(9S) structure. An
818  * HBA driver will then initialize the structure and then call
819  * scsi_hba_attach_setup(9F).
820  */
821 /*ARGSUSED*/
822 scsi_hba_tran_t *
823 scsi_hba_tran_alloc(
824 	dev_info_t		*self,
825 	int			flags)
826 {
827 	scsi_hba_tran_t		*tran;
828 
829 	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
830 
831 	/* allocate SCSA flavors for self */
832 	ndi_flavorv_alloc(self, SCSA_NFLAVORS);
833 
834 	tran = kmem_zalloc(sizeof (scsi_hba_tran_t),
835 	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
836 
837 	if (tran) {
838 		tran->tran_interconnect_type = INTERCONNECT_PARALLEL;
839 
840 		/*
841 		 * HBA driver called scsi_hba_tran_alloc(), so tran structure
842 		 * is proper size and unused/newer fields are zero.
843 		 *
844 		 * NOTE: We use SCSA_HBA_SCSA_TA as an obtuse form of
845 		 * versioning to detect old HBA drivers that do not use
846 		 * scsi_hba_tran_alloc, and would present garbage data
847 		 * (instead of valid/zero data) for newer tran fields.
848 		 */
849 		tran->tran_hba_flags |= SCSI_HBA_SCSA_TA;
850 	}
851 
852 	return (tran);
853 }
854 
855 /*
856  * Called by an HBA to free a scsi_hba_tran structure
857  */
858 void
859 scsi_hba_tran_free(
860 	scsi_hba_tran_t		*tran)
861 {
862 	SCSI_HBA_LOG((_LOG_TRACE, tran->tran_hba_dip, NULL, __func__));
863 
864 	kmem_free(tran, sizeof (scsi_hba_tran_t));
865 }
866 
867 int
868 scsi_tran_ext_alloc(
869 	scsi_hba_tran_t		*tran,
870 	size_t			length,
871 	int			flags)
872 {
873 	void	*tran_ext;
874 	int	ret = DDI_FAILURE;
875 
876 	tran_ext = kmem_zalloc(length,
877 	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
878 	if (tran_ext != NULL) {
879 		tran->tran_extension = tran_ext;
880 		ret = DDI_SUCCESS;
881 	}
882 	return (ret);
883 }
884 
885 void
886 scsi_tran_ext_free(
887 	scsi_hba_tran_t		*tran,
888 	size_t			length)
889 {
890 	if (tran->tran_extension != NULL) {
891 		kmem_free(tran->tran_extension, length);
892 		tran->tran_extension = NULL;
893 	}
894 }
895 
896 /*
897  * Obsolete: Called by an HBA to attach an instance of the driver
898  * Implement this older interface in terms of the new.
899  */
900 /*ARGSUSED*/
901 int
902 scsi_hba_attach(
903 	dev_info_t		*self,
904 	ddi_dma_lim_t		*hba_lim,
905 	scsi_hba_tran_t		*tran,
906 	int			flags,
907 	void			*hba_options)
908 {
909 	ddi_dma_attr_t		hba_dma_attr;
910 
911 	bzero(&hba_dma_attr, sizeof (ddi_dma_attr_t));
912 	hba_dma_attr.dma_attr_burstsizes = hba_lim->dlim_burstsizes;
913 	hba_dma_attr.dma_attr_minxfer = hba_lim->dlim_minxfer;
914 
915 	return (scsi_hba_attach_setup(self, &hba_dma_attr, tran, flags));
916 }
917 
918 /*
919  * Common nexus teardown code: used by both scsi_hba_detach() on SCSA HBA node
920  * and iport_postdetach_tran_scsi_device() on a SCSA HBA iport node (and for
921  * failure cleanup). Undo scsa_nexus_setup in reverse order.
922  *
923  * NOTE: Since we are in the Solaris IO framework, we can depend on
924  * undocumented cleanup operations performed by other parts of the framework:
925  * like detach_node() calling ddi_prop_remove_all() and
926  * ddi_remove_minor_node(,NULL).
927  */
928 static void
929 scsa_nexus_teardown(dev_info_t *self, scsi_hba_tran_t	*tran)
930 {
931 	/* Teardown FMA. */
932 	if (tran->tran_hba_flags & SCSI_HBA_SCSA_FM) {
933 		ddi_fm_fini(self);
934 		tran->tran_hba_flags &= ~SCSI_HBA_SCSA_FM;
935 	}
936 }
937 
938 /*
939  * Common nexus setup code: used by both scsi_hba_attach_setup() on SCSA HBA
940  * node and iport_preattach_tran_scsi_device() on a SCSA HBA iport node.
941  *
942  * This code makes no assumptions about tran use by scsi_device children.
943  */
944 static int
945 scsa_nexus_setup(dev_info_t *self, scsi_hba_tran_t *tran)
946 {
947 	int		capable;
948 	int		scsa_minor;
949 
950 	/*
951 	 * NOTE: SCSA maintains an 'fm-capable' domain, in tran_fm_capable,
952 	 * that is not dependent (limited by) the capabilities of its parents.
953 	 * For example a devinfo node in a branch that is not
954 	 * DDI_FM_EREPORT_CAPABLE may report as capable, via tran_fm_capable,
955 	 * to its scsi_device children.
956 	 *
957 	 * Get 'fm-capable' property from driver.conf, if present. If not
958 	 * present, default to the scsi_fm_capable global (which has
959 	 * DDI_FM_EREPORT_CAPABLE set by default).
960 	 */
961 	if (tran->tran_fm_capable == DDI_FM_NOT_CAPABLE)
962 		tran->tran_fm_capable = ddi_prop_get_int(DDI_DEV_T_ANY, self,
963 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
964 		    "fm-capable", scsi_fm_capable);
965 
966 	/*
967 	 * If an HBA is *not* doing its own fma support by calling
968 	 * ddi_fm_init() prior to scsi_hba_attach_setup(), we provide a minimal
969 	 * common SCSA implementation so that scsi_device children can generate
970 	 * ereports via scsi_fm_ereport_post().  We use ddi_fm_capable() to
971 	 * detect an HBA calling ddi_fm_init() prior to scsi_hba_attach_setup().
972 	 */
973 	if (tran->tran_fm_capable &&
974 	    (ddi_fm_capable(self) == DDI_FM_NOT_CAPABLE)) {
975 		/*
976 		 * We are capable of something, pass our capabilities up the
977 		 * tree, but use a local variable so our parent can't limit
978 		 * our capabilities (we don't want our parent to clear
979 		 * DDI_FM_EREPORT_CAPABLE).
980 		 *
981 		 * NOTE: iblock cookies are not important because scsi HBAs
982 		 * always interrupt below LOCK_LEVEL.
983 		 */
984 		capable = tran->tran_fm_capable;
985 		ddi_fm_init(self, &capable, NULL);
986 
987 		/*
988 		 * Set SCSI_HBA_SCSA_FM bit to mark us as using the common
989 		 * minimal SCSA fm implementation -  we called ddi_fm_init(),
990 		 * so we are responsible for calling ddi_fm_fini() in
991 		 * scsi_hba_detach().
992 		 *
993 		 * NOTE: if ddi_fm_init fails to establish handle, SKIP cleanup.
994 		 */
995 		if (DEVI(self)->devi_fmhdl)
996 			tran->tran_hba_flags |= SCSI_HBA_SCSA_FM;
997 	}
998 
999 	/* If SCSA responsible for for minor nodes, create :devctl minor. */
1000 	scsa_minor = (ddi_get_driver(self)->devo_cb_ops->cb_open ==
1001 	    scsi_hba_open) ? 1 : 0;
1002 	if (scsa_minor && ((ddi_create_minor_node(self, "devctl", S_IFCHR,
1003 	    INST2DEVCTL(ddi_get_instance(self)), DDI_NT_SCSI_NEXUS, 0) !=
1004 	    DDI_SUCCESS))) {
1005 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1006 		    "can't create :devctl minor node"));
1007 		goto fail;
1008 	}
1009 
1010 	return (DDI_SUCCESS);
1011 
1012 fail:	scsa_nexus_teardown(self, tran);
1013 	return (DDI_FAILURE);
1014 }
1015 
1016 /*
1017  * Common tran teardown code: used by iport_postdetach_tran_scsi_device() on a
1018  * SCSA HBA iport node and (possibly) by scsi_hba_detach() on SCSA HBA node
1019  * (and for failure cleanup). Undo scsa_tran_setup in reverse order.
1020  *
1021  * NOTE: Since we are in the Solaris IO framework, we can depend on
1022  * undocumented cleanup operations performed by other parts of the framework:
1023  * like detach_node() calling ddi_prop_remove_all() and
1024  * ddi_remove_minor_node(,NULL).
1025  */
1026 static void
1027 scsa_tran_teardown(dev_info_t *self, scsi_hba_tran_t *tran)
1028 {
1029 	tran->tran_iport_dip = NULL;
1030 
1031 	/* Teardown pHCI registration */
1032 	if (tran->tran_hba_flags & SCSI_HBA_SCSA_PHCI) {
1033 		(void) mdi_phci_unregister(self, 0);
1034 		tran->tran_hba_flags &= ~SCSI_HBA_SCSA_PHCI;
1035 	}
1036 }
1037 
1038 /*
1039  * Common tran setup code: used by iport_preattach_tran_scsi_device() on a
1040  * SCSA HBA iport node and (possibly) by scsi_hba_attach_setup() on SCSA HBA
1041  * node.
1042  */
1043 static int
1044 scsa_tran_setup(dev_info_t *self, scsi_hba_tran_t *tran)
1045 {
1046 	int			scsa_minor;
1047 	int			id;
1048 	char			*scsi_binding_set;
1049 	static const char	*interconnect[] = INTERCONNECT_TYPE_ASCII;
1050 
1051 	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
1052 
1053 	/* If SCSA responsible for for minor nodes, create ":scsi" */
1054 	scsa_minor = (ddi_get_driver(self)->devo_cb_ops->cb_open ==
1055 	    scsi_hba_open) ? 1 : 0;
1056 	if (scsa_minor && (ddi_create_minor_node(self, "scsi", S_IFCHR,
1057 	    INST2SCSI(ddi_get_instance(self)),
1058 	    DDI_NT_SCSI_ATTACHMENT_POINT, 0) != DDI_SUCCESS)) {
1059 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1060 		    "can't create :scsi minor node"));
1061 		goto fail;
1062 	}
1063 
1064 	/*
1065 	 * If the property does not already exist on self then see if we can
1066 	 * pull it from further up the tree and define it on self. If the
1067 	 * property does not exist above (including options.conf) then use the
1068 	 * default value specified (global variable). We pull things down from
1069 	 * above for faster "DDI_PROP_NOTPROM | DDI_PROP_DONTPASS" runtime
1070 	 * access.
1071 	 *
1072 	 * Future: Should we avoid creating properties when value == global?
1073 	 */
1074 #define	CONFIG_INT_PROP(s, p, dv)	{			\
1075 	if ((ddi_prop_exists(DDI_DEV_T_ANY, s,			\
1076 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, p) == 0) &&	\
1077 	    (ndi_prop_update_int(DDI_DEV_T_NONE, s, p,		\
1078 	    ddi_prop_get_int(DDI_DEV_T_ANY, ddi_get_parent(s),	\
1079 	    DDI_PROP_NOTPROM, p, dv)) != DDI_PROP_SUCCESS))	\
1080 		SCSI_HBA_LOG((_LOG(WARN), NULL, s,		\
1081 		    "can't create property '%s'", p));		\
1082 	}
1083 
1084 	/* Decorate with scsi configuration properties */
1085 	CONFIG_INT_PROP(self, "scsi-enumeration", scsi_enumeration);
1086 	CONFIG_INT_PROP(self, "scsi-options", scsi_options);
1087 	CONFIG_INT_PROP(self, "scsi-reset-delay", scsi_reset_delay);
1088 	CONFIG_INT_PROP(self, "scsi-watchdog-tick", scsi_watchdog_tick);
1089 	CONFIG_INT_PROP(self, "scsi-selection-timeout", scsi_selection_timeout);
1090 	CONFIG_INT_PROP(self, "scsi-tag-age-limit", scsi_tag_age_limit);
1091 
1092 	/*
1093 	 * Pull down the scsi-initiator-id from further up the tree, or as
1094 	 * defined by OBP. Place on node for faster access. NOTE: there is
1095 	 * some confusion about what the name of the property should be.
1096 	 */
1097 	id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0, "initiator-id", -1);
1098 	if (id == -1)
1099 		id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0,
1100 		    "scsi-initiator-id", -1);
1101 	if (id != -1)
1102 		CONFIG_INT_PROP(self, "scsi-initiator-id", id);
1103 
1104 	/*
1105 	 * If we are responsible for tran allocation, establish
1106 	 * 'initiator-interconnect-type'.
1107 	 */
1108 	if ((tran->tran_hba_flags & SCSI_HBA_SCSA_TA) &&
1109 	    (tran->tran_interconnect_type > 0) &&
1110 	    (tran->tran_interconnect_type < INTERCONNECT_MAX)) {
1111 		if (ndi_prop_update_string(DDI_DEV_T_NONE, self,
1112 		    "initiator-interconnect-type",
1113 		    (char *)interconnect[tran->tran_interconnect_type])
1114 		    != DDI_PROP_SUCCESS) {
1115 			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1116 			    "failed to establish "
1117 			    "'initiator-interconnect-type'"));
1118 			goto fail;
1119 		}
1120 	}
1121 
1122 	/*
1123 	 * The 'scsi-binding-set' property can be defined in driver.conf
1124 	 * files of legacy drivers on an as-needed basis. If 'scsi-binding-set'
1125 	 * is not driver.conf defined, and the HBA is not implementing its own
1126 	 * private bus_config, we define scsi-binding-set to the default
1127 	 * 'spi' legacy value.
1128 	 *
1129 	 * NOTE: This default 'spi' value will be deleted if an HBA driver
1130 	 * ends up using the scsi_hba_tgtmap_create() enumeration services.
1131 	 *
1132 	 * NOTE: If we were ever to decide to derive 'scsi-binding-set' from
1133 	 * the IEEE-1275 'device_type' property then this is where that code
1134 	 * should go - there is not enough consistency in 'device_type' to do
1135 	 * this correctly at this point in time.
1136 	 */
1137 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
1138 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-binding-set",
1139 	    &scsi_binding_set) == DDI_PROP_SUCCESS) {
1140 		SCSI_HBA_LOG((_LOG(2), NULL, self,
1141 		    "external 'scsi-binding-set' \"%s\"", scsi_binding_set));
1142 		ddi_prop_free(scsi_binding_set);
1143 	} else if (scsi_binding_set_spi &&
1144 	    ((tran->tran_bus_config == NULL) ||
1145 	    (tran->tran_bus_config == scsi_hba_bus_config_spi))) {
1146 		if (ndi_prop_update_string(DDI_DEV_T_NONE, self,
1147 		    "scsi-binding-set", scsi_binding_set_spi) !=
1148 		    DDI_PROP_SUCCESS) {
1149 			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1150 			    "failed to establish 'scsi_binding_set' default"));
1151 			goto fail;
1152 		}
1153 		SCSI_HBA_LOG((_LOG(2), NULL, self,
1154 		    "default 'scsi-binding-set' \"%s\"", scsi_binding_set_spi));
1155 	} else
1156 		SCSI_HBA_LOG((_LOG(2), NULL, self,
1157 		    "no 'scsi-binding-set'"));
1158 
1159 	/*
1160 	 * If SCSI_HBA_TRAN_PHCI is set, take care of pHCI registration of the
1161 	 * initiator.
1162 	 */
1163 	if ((tran->tran_hba_flags & SCSI_HBA_TRAN_PHCI) &&
1164 	    (mdi_phci_register(MDI_HCI_CLASS_SCSI, self, 0) == MDI_SUCCESS))
1165 		tran->tran_hba_flags |= SCSI_HBA_SCSA_PHCI;
1166 
1167 	/* NOTE: tran_hba_dip is for DMA operation at the HBA node level */
1168 	tran->tran_iport_dip = self;		/* for iport association */
1169 	return (DDI_SUCCESS);
1170 
1171 fail:	scsa_tran_teardown(self, tran);
1172 	return (DDI_FAILURE);
1173 }
1174 
1175 /*
1176  * Called by a SCSA HBA driver to attach an instance of the driver to
1177  * SCSA HBA node  enumerated by PCI.
1178  */
1179 int
1180 scsi_hba_attach_setup(
1181 	dev_info_t		*self,
1182 	ddi_dma_attr_t		*hba_dma_attr,
1183 	scsi_hba_tran_t		*tran,
1184 	int			flags)
1185 {
1186 	int			len;
1187 	char			cache_name[96];
1188 
1189 	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
1190 
1191 	/*
1192 	 * Verify that we are a driver so other code does not need to
1193 	 * check for NULL ddi_get_driver() result.
1194 	 */
1195 	if (ddi_get_driver(self) == NULL)
1196 		return (DDI_FAILURE);
1197 
1198 	/*
1199 	 * Verify that we are called on a SCSA HBA node (function enumerated
1200 	 * by PCI), not on an iport node.
1201 	 */
1202 	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1203 	if (scsi_hba_iport_unit_address(self))
1204 		return (DDI_FAILURE);		/* self can't be an iport */
1205 
1206 	/* Caller must provide the tran. */
1207 	ASSERT(tran);
1208 	if (tran == NULL)
1209 		return (DDI_FAILURE);
1210 
1211 	/*
1212 	 * Verify correct scsi_hba_tran_t form:
1213 	 *
1214 	 * o Both or none of tran_get_name/tran_get_addr.
1215 	 *   NOTE: Older  SCSA HBA drivers for SCSI transports with addressing
1216 	 *   that did not fit the SPI "struct scsi_address" model were required
1217 	 *   to implement tran_get_name and tran_get_addr. This is no longer
1218 	 *   true - modern transport drivers should now use common SCSA
1219 	 *   enumeration services.  The SCSA enumeration code will represent
1220 	 *   the unit-address using well-known address properties
1221 	 *   (SCSI_ADDR_PROP_TARGET_PORT, SCSI_ADDR_PROP_LUN64) during
1222 	 *   devinfo/pathinfo node creation. The HBA driver can obtain values
1223 	 *   using scsi_device_prop_lookup_*() from its tran_tgt_init(9E).
1224 	 *
1225 	 */
1226 	if ((tran->tran_get_name == NULL) ^ (tran->tran_get_bus_addr == NULL)) {
1227 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1228 		    "should support both or neither: "
1229 		    "tran_get_name, tran_get_bus_addr"));
1230 		return (DDI_FAILURE);
1231 	}
1232 
1233 	/*
1234 	 * Establish the devinfo context of this tran structure, preserving
1235 	 * knowledge of how the tran was allocated.
1236 	 */
1237 	tran->tran_hba_dip = self;		/* for DMA */
1238 	tran->tran_hba_flags = (flags & ~SCSI_HBA_SCSA_TA) |
1239 	    (tran->tran_hba_flags & SCSI_HBA_SCSA_TA);
1240 
1241 	/* Establish flavor of transport (and ddi_get_driver_private()) */
1242 	ndi_flavorv_set(self, SCSA_FLAVOR_SCSI_DEVICE, tran);
1243 
1244 	/*
1245 	 * Note: We only need dma_attr_minxfer and dma_attr_burstsizes
1246 	 * from the DMA attributes. scsi_hba_attach(9f) only guarantees
1247 	 * that these two fields are initialized properly. If this
1248 	 * changes, be sure to revisit the implementation of
1249 	 * scsi_hba_attach(9F).
1250 	 */
1251 	(void) memcpy(&tran->tran_dma_attr, hba_dma_attr,
1252 	    sizeof (ddi_dma_attr_t));
1253 
1254 	/* Create tran_setup_pkt(9E) kmem_cache. */
1255 	if (tran->tran_setup_pkt) {
1256 		ASSERT(tran->tran_init_pkt == NULL);
1257 		ASSERT(tran->tran_destroy_pkt == NULL);
1258 		if (tran->tran_init_pkt || tran->tran_destroy_pkt)
1259 			goto fail;
1260 
1261 		tran->tran_init_pkt = scsi_init_cache_pkt;
1262 		tran->tran_destroy_pkt = scsi_free_cache_pkt;
1263 		tran->tran_sync_pkt = scsi_sync_cache_pkt;
1264 		tran->tran_dmafree = scsi_cache_dmafree;
1265 
1266 		len = sizeof (struct scsi_pkt_cache_wrapper);
1267 		len += ROUNDUP(tran->tran_hba_len);
1268 		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB)
1269 			len += ROUNDUP(DEFAULT_CDBLEN);
1270 		if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
1271 			len += ROUNDUP(DEFAULT_SCBLEN);
1272 
1273 		(void) snprintf(cache_name, sizeof (cache_name),
1274 		    "pkt_cache_%s_%d", ddi_driver_name(self),
1275 		    ddi_get_instance(self));
1276 
1277 		tran->tran_pkt_cache_ptr = kmem_cache_create(
1278 		    cache_name, len, 8, scsi_hba_pkt_constructor,
1279 		    scsi_hba_pkt_destructor, NULL, tran, NULL, 0);
1280 	}
1281 
1282 	/* Perform node setup independent of initiator role */
1283 	if (scsa_nexus_setup(self, tran) != DDI_SUCCESS)
1284 		goto fail;
1285 
1286 	/*
1287 	 * The SCSI_HBA_HBA flag is passed to scsi_hba_attach_setup when the
1288 	 * HBA driver knows that *all* children of the SCSA HBA node will be
1289 	 * 'iports'. If the SCSA HBA node can have iport children and also
1290 	 * function as an initiator for xxx_device children then it should
1291 	 * not specify SCSI_HBA_HBA in its scsi_hba_attach_setup call. An
1292 	 * HBA driver that does not manage iports should not set SCSA_HBA_HBA.
1293 	 */
1294 	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
1295 		/*
1296 		 * Set the 'ddi-config-driver-node' property on the nexus
1297 		 * node that notify attach_driver_nodes() to configure all
1298 		 * immediate children so that nodes which bind to the
1299 		 * same driver as parent are able to be added into per-driver
1300 		 * list.
1301 		 */
1302 		if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
1303 		    self, "ddi-config-driver-node") != DDI_PROP_SUCCESS)
1304 			goto fail;
1305 	} else {
1306 		if (scsa_tran_setup(self, tran) != DDI_SUCCESS)
1307 			goto fail;
1308 	}
1309 
1310 	return (DDI_SUCCESS);
1311 
1312 fail:	(void) scsi_hba_detach(self);
1313 	return (DDI_FAILURE);
1314 }
1315 
1316 /*
1317  * Called by an HBA to detach an instance of the driver. This may be called
1318  * for SCSA HBA nodes and for SCSA iport nodes.
1319  */
1320 int
1321 scsi_hba_detach(dev_info_t *self)
1322 {
1323 	scsi_hba_tran_t		*tran;
1324 
1325 	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1326 	if (scsi_hba_iport_unit_address(self))
1327 		return (DDI_FAILURE);		/* self can't be an iport */
1328 
1329 	/* Check all error return conditions upfront */
1330 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1331 	ASSERT(tran);
1332 	if (tran == NULL)
1333 		return (DDI_FAILURE);
1334 
1335 	ASSERT(tran->tran_open_flag == 0);
1336 	if (tran->tran_open_flag)
1337 		return (DDI_FAILURE);
1338 
1339 	if (!(tran->tran_hba_flags & SCSI_HBA_HBA))
1340 		scsa_tran_teardown(self, tran);
1341 	scsa_nexus_teardown(self, tran);
1342 
1343 	/* Teardown tran_setup_pkt(9E) kmem_cache. */
1344 	if (tran->tran_pkt_cache_ptr) {
1345 		kmem_cache_destroy(tran->tran_pkt_cache_ptr);
1346 		tran->tran_pkt_cache_ptr = NULL;
1347 	}
1348 
1349 	(void) memset(&tran->tran_dma_attr, 0, sizeof (ddi_dma_attr_t));
1350 
1351 	/* Teardown flavor of transport (and ddi_get_driver_private()) */
1352 	ndi_flavorv_set(self, SCSA_FLAVOR_SCSI_DEVICE, NULL);
1353 
1354 	tran->tran_hba_dip = NULL;
1355 
1356 	return (DDI_SUCCESS);
1357 }
1358 
1359 
1360 /*
1361  * Called by an HBA from _fini()
1362  */
1363 void
1364 scsi_hba_fini(struct modlinkage *modlp)
1365 {
1366 	struct dev_ops *hba_dev_ops;
1367 
1368 	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
1369 
1370 	/* Get the devops structure of this module and clear bus_ops vector. */
1371 	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
1372 
1373 	if (hba_dev_ops->devo_cb_ops == &scsi_hba_cbops)
1374 		hba_dev_ops->devo_cb_ops = NULL;
1375 
1376 	if (hba_dev_ops->devo_getinfo == scsi_hba_info)
1377 		hba_dev_ops->devo_getinfo = NULL;
1378 
1379 	hba_dev_ops->devo_bus_ops = (struct bus_ops *)NULL;
1380 }
1381 
1382 /*
1383  * SAS specific functions
1384  */
1385 smp_hba_tran_t *
1386 smp_hba_tran_alloc(dev_info_t *self)
1387 {
1388 	/* allocate SCSA flavors for self */
1389 	ndi_flavorv_alloc(self, SCSA_NFLAVORS);
1390 	return (kmem_zalloc(sizeof (smp_hba_tran_t), KM_SLEEP));
1391 }
1392 
1393 void
1394 smp_hba_tran_free(smp_hba_tran_t *tran)
1395 {
1396 	kmem_free(tran, sizeof (smp_hba_tran_t));
1397 }
1398 
1399 int
1400 smp_hba_attach_setup(
1401 	dev_info_t		*self,
1402 	smp_hba_tran_t		*tran)
1403 {
1404 	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1405 	if (scsi_hba_iport_unit_address(self))
1406 		return (DDI_FAILURE);		/* self can't be an iport */
1407 
1408 	/*
1409 	 * The owner of the this devinfo_t was responsible
1410 	 * for informing the framework already about
1411 	 * additional flavors.
1412 	 */
1413 	ndi_flavorv_set(self, SCSA_FLAVOR_SMP, tran);
1414 	return (DDI_SUCCESS);
1415 }
1416 
1417 int
1418 smp_hba_detach(dev_info_t *self)
1419 {
1420 	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1421 	if (scsi_hba_iport_unit_address(self))
1422 		return (DDI_FAILURE);		/* self can't be an iport */
1423 
1424 	ndi_flavorv_set(self, SCSA_FLAVOR_SMP, NULL);
1425 	return (DDI_SUCCESS);
1426 }
1427 
1428 /*
1429  * SMP child flavored functions
1430  */
1431 static int
1432 smp_busctl_ua(dev_info_t *child, char *addr, int maxlen)
1433 {
1434 	char		*tport;
1435 	char		*wwn;
1436 
1437 	/* limit ndi_devi_findchild_by_callback to expected flavor */
1438 	if (ndi_flavor_get(child) != SCSA_FLAVOR_SMP)
1439 		return (DDI_FAILURE);
1440 
1441 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1442 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1443 	    SCSI_ADDR_PROP_TARGET_PORT, &tport) == DDI_SUCCESS) {
1444 		(void) snprintf(addr, maxlen, "%s", tport);
1445 		ddi_prop_free(tport);
1446 		return (DDI_SUCCESS);
1447 	}
1448 
1449 	/*
1450 	 * NOTE: the following code should be deleted when mpt is changed to
1451 	 * use SCSI_ADDR_PROP_TARGET_PORT instead of SMP_WWN.
1452 	 */
1453 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1454 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1455 	    SMP_WWN, &wwn) == DDI_SUCCESS) {
1456 		(void) snprintf(addr, maxlen, "w%s", wwn);
1457 		ddi_prop_free(wwn);
1458 		return (DDI_SUCCESS);
1459 	}
1460 	return (DDI_FAILURE);
1461 }
1462 
1463 static int
1464 smp_busctl_reportdev(dev_info_t *child)
1465 {
1466 	dev_info_t	*self = ddi_get_parent(child);
1467 	char		*tport;
1468 	char		*wwn;
1469 
1470 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1471 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1472 	    SCSI_ADDR_PROP_TARGET_PORT, &tport) == DDI_SUCCESS) {
1473 		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: target-port %s",
1474 		    ddi_driver_name(child), ddi_get_instance(child),
1475 		    ddi_driver_name(self), ddi_get_instance(self), tport));
1476 		ddi_prop_free(tport);
1477 		return (DDI_SUCCESS);
1478 	}
1479 
1480 	/*
1481 	 * NOTE: the following code should be deleted when mpt is changed to
1482 	 * use SCSI_ADDR_PROP_TARGET_PORT instead of SMP_WWN.
1483 	 */
1484 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1485 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1486 	    SMP_WWN, &wwn) == DDI_SUCCESS) {
1487 		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: wwn %s",
1488 		    ddi_driver_name(child), ddi_get_instance(child),
1489 		    ddi_driver_name(self), ddi_get_instance(self), wwn));
1490 		ddi_prop_free(wwn);
1491 		return (DDI_SUCCESS);
1492 	}
1493 	return (DDI_FAILURE);
1494 }
1495 
1496 static int
1497 smp_busctl_initchild(dev_info_t *child)
1498 {
1499 	dev_info_t		*self = ddi_get_parent(child);
1500 	smp_hba_tran_t		*tran;
1501 	dev_info_t		*dup;
1502 	char			addr[SCSI_MAXNAMELEN];
1503 	struct smp_device	*smp_sd;
1504 	uint64_t		wwn;
1505 
1506 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SMP);
1507 	ASSERT(tran);
1508 	if (tran == NULL)
1509 		return (DDI_FAILURE);
1510 
1511 	if (smp_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS)
1512 		return (DDI_NOT_WELL_FORMED);
1513 	if (scsi_wwnstr_to_wwn(addr, &wwn))
1514 		return (DDI_NOT_WELL_FORMED);
1515 
1516 	/* Prevent duplicate nodes.  */
1517 	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
1518 	    smp_busctl_ua);
1519 	if (dup) {
1520 		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_SMP);
1521 		if (ndi_flavor_get(dup) != SCSA_FLAVOR_SMP) {
1522 			SCSI_HBA_LOG((_LOG(1), NULL, child,
1523 			    "init failed: %s@%s: not SMP flavored",
1524 			    ddi_node_name(child), addr));
1525 			return (DDI_FAILURE);
1526 		}
1527 		if (dup != child) {
1528 			SCSI_HBA_LOG((_LOG(4), NULL, child,
1529 			    "init failed: %s@%s: detected duplicate %p",
1530 			    ddi_node_name(child), addr, (void *)dup));
1531 			return (DDI_FAILURE);
1532 		}
1533 	}
1534 
1535 
1536 	/* set the node @addr string */
1537 	ddi_set_name_addr(child, addr);
1538 
1539 	/* Allocate and initialize smp_device. */
1540 	smp_sd = kmem_zalloc(sizeof (struct smp_device), KM_SLEEP);
1541 	smp_sd->smp_sd_dev = child;
1542 	smp_sd->smp_sd_address.smp_a_hba_tran = tran;
1543 	bcopy(&wwn, smp_sd->smp_sd_address.smp_a_wwn, SAS_WWN_BYTE_SIZE);
1544 
1545 	ddi_set_driver_private(child, smp_sd);
1546 
1547 	if (tran->smp_tran_init && ((*tran->smp_tran_init)(self, child,
1548 	    tran, smp_sd) != DDI_SUCCESS)) {
1549 		kmem_free(smp_sd, sizeof (struct smp_device));
1550 		if (ndi_dev_is_hotplug_node(child))
1551 			SCSI_HBA_LOG((_LOG(WARN), NULL, child,
1552 			    "enumeration failed during smp_tran_init"));
1553 		else
1554 			SCSI_HBA_LOG((_LOG(2), NULL, child,
1555 			    "enumeration failed during smp_tran_init"));
1556 		ddi_set_driver_private(child, NULL);
1557 		ddi_set_name_addr(child, NULL);
1558 		return (DDI_FAILURE);
1559 	}
1560 
1561 	return (DDI_SUCCESS);
1562 }
1563 
1564 /*ARGSUSED*/
1565 static int
1566 smp_busctl_uninitchild(dev_info_t *child)
1567 {
1568 	dev_info_t		*self = ddi_get_parent(child);
1569 	struct smp_device	*smp_sd = ddi_get_driver_private(child);
1570 	smp_hba_tran_t		*tran;
1571 
1572 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SMP);
1573 	ASSERT(smp_sd && tran);
1574 	if ((smp_sd == NULL) || (tran == NULL))
1575 		return (DDI_FAILURE);
1576 
1577 	if (tran->smp_tran_free)
1578 		(*tran->smp_tran_free) (self, child, tran, smp_sd);
1579 
1580 	kmem_free(smp_sd, sizeof (*smp_sd));
1581 	ddi_set_driver_private(child, NULL);
1582 	ddi_set_name_addr(child, NULL);
1583 	return (DDI_SUCCESS);
1584 }
1585 
1586 /* Find an "smp" child at the specified address. */
1587 static dev_info_t *
1588 smp_hba_find_child(dev_info_t *self, char *addr)
1589 {
1590 	dev_info_t	*child;
1591 
1592 	/* Search "smp" devinfo child at specified address. */
1593 	ASSERT(self && DEVI_BUSY_OWNED(self) && addr);
1594 	for (child = ddi_get_child(self); child;
1595 	    child = ddi_get_next_sibling(child)) {
1596 		/* skip non-"smp" nodes */
1597 		if (ndi_flavor_get(child) != SCSA_FLAVOR_SMP)
1598 			continue;
1599 
1600 		/* Attempt initchild to establish unit-address */
1601 		if (i_ddi_node_state(child) < DS_INITIALIZED)
1602 			(void) ddi_initchild(self, child);
1603 
1604 		/* Verify state and non-NULL unit-address. */
1605 		if ((i_ddi_node_state(child) < DS_INITIALIZED) ||
1606 		    (ddi_get_name_addr(child) == NULL))
1607 			continue;
1608 
1609 		/* Return "smp" child if unit-address matches. */
1610 		if (strcmp(ddi_get_name_addr(child), addr) == 0)
1611 			return (child);
1612 	}
1613 	return (NULL);
1614 }
1615 
1616 /*
1617  * Search for "smp" child of self at the specified address. If found, online
1618  * and return with a hold.  Unlike general SCSI configuration, we can assume
1619  * the the device is actually there when we are called (i.e., device is
1620  * created by hotplug, not by bus_config).
1621  */
1622 int
1623 smp_hba_bus_config(dev_info_t *self, char *addr, dev_info_t **childp)
1624 {
1625 	dev_info_t	*child;
1626 	int		circ;
1627 
1628 	ASSERT(self && addr && childp);
1629 	*childp = NULL;
1630 
1631 	/* Search for "smp" child. */
1632 	scsi_hba_devi_enter(self, &circ);
1633 	if ((child = smp_hba_find_child(self, addr)) == NULL) {
1634 		scsi_hba_devi_exit(self, circ);
1635 		return (NDI_FAILURE);
1636 	}
1637 
1638 	/* Attempt online. */
1639 	if (ndi_devi_online(child, 0) != NDI_SUCCESS) {
1640 		scsi_hba_devi_exit(self, circ);
1641 		return (NDI_FAILURE);
1642 	}
1643 
1644 	/* On success, return with active hold. */
1645 	ndi_hold_devi(child);
1646 	scsi_hba_devi_exit(self, circ);
1647 	*childp = child;
1648 	return (NDI_SUCCESS);
1649 }
1650 
1651 
1652 
1653 /* Create "smp" child devinfo node at specified unit-address. */
1654 int
1655 smp_hba_bus_config_taddr(dev_info_t *self, char *addr)
1656 {
1657 	dev_info_t		*child;
1658 	int			circ;
1659 
1660 	/*
1661 	 * NOTE: If we ever uses a generic node name (.vs. a driver name)
1662 	 * or define a 'compatible' property, this code will need to use
1663 	 * a 'probe' node (ala scsi_device support) to obtain identity
1664 	 * information from the device.
1665 	 */
1666 
1667 	/* Search for "smp" child. */
1668 	scsi_hba_devi_enter(self, &circ);
1669 	child = smp_hba_find_child(self, addr);
1670 	if (child) {
1671 		/* Child exists, note if this was a new reinsert. */
1672 		if (ndi_devi_device_insert(child))
1673 			SCSI_HBA_LOG((_LOGCFG, self, NULL,
1674 			    "devinfo smp@%s device_reinsert", addr));
1675 
1676 		scsi_hba_devi_exit(self, circ);
1677 		return (NDI_SUCCESS);
1678 	}
1679 
1680 	/* Allocate "smp" child devinfo node and establish flavor of child. */
1681 	ndi_devi_alloc_sleep(self, "smp", DEVI_SID_HP_NODEID, &child);
1682 	ASSERT(child);
1683 	ndi_flavor_set(child, SCSA_FLAVOR_SMP);
1684 
1685 	/* Add unit-address property to child. */
1686 	if (ndi_prop_update_string(DDI_DEV_T_NONE, child,
1687 	    SCSI_ADDR_PROP_TARGET_PORT, addr) != DDI_PROP_SUCCESS) {
1688 		(void) ndi_devi_free(child);
1689 		scsi_hba_devi_exit(self, circ);
1690 		return (NDI_FAILURE);
1691 	}
1692 
1693 	/* Attempt to online the new "smp" node. */
1694 	(void) ndi_devi_online(child, 0);
1695 
1696 	scsi_hba_devi_exit(self, circ);
1697 	return (NDI_SUCCESS);
1698 }
1699 
1700 /*
1701  * Wrapper to scsi_ua_get which takes a devinfo argument instead of a
1702  * scsi_device structure.
1703  */
1704 static int
1705 scsi_busctl_ua(dev_info_t *child, char *addr, int maxlen)
1706 {
1707 	struct scsi_device	*sd;
1708 
1709 	/* limit ndi_devi_findchild_by_callback to expected flavor */
1710 	if (ndi_flavor_get(child) != SCSA_FLAVOR_SCSI_DEVICE)
1711 		return (DDI_FAILURE);
1712 
1713 	/* nodes are named by tran_get_name or default "tgt,lun" */
1714 	sd = ddi_get_driver_private(child);
1715 	if (sd && (scsi_ua_get(sd, addr, maxlen) == 1))
1716 		return (DDI_SUCCESS);
1717 
1718 	return (DDI_FAILURE);
1719 }
1720 
1721 static int
1722 scsi_busctl_reportdev(dev_info_t *child)
1723 {
1724 	dev_info_t		*self = ddi_get_parent(child);
1725 	struct scsi_device	*sd = ddi_get_driver_private(child);
1726 	scsi_hba_tran_t		*tran;
1727 	char			ua[SCSI_MAXNAMELEN];
1728 	char			ra[SCSI_MAXNAMELEN];
1729 
1730 	SCSI_HBA_LOG((_LOG_TRACE, NULL, child, __func__));
1731 
1732 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1733 	ASSERT(tran && sd);
1734 	if ((tran == NULL) || (sd == NULL))
1735 		return (DDI_FAILURE);
1736 
1737 	/* get the unit_address and bus_addr information */
1738 	if ((scsi_ua_get(sd, ua, sizeof (ua)) == 0) ||
1739 	    (scsi_ua_get_reportdev(sd, ra, sizeof (ra)) == 0)) {
1740 		SCSI_HBA_LOG((_LOG(WARN), NULL, child, "REPORTDEV failure"));
1741 		return (DDI_FAILURE);
1742 	}
1743 
1744 	if (tran->tran_get_name == NULL)
1745 		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: %s",
1746 		    ddi_driver_name(child), ddi_get_instance(child),
1747 		    ddi_driver_name(self), ddi_get_instance(self), ra));
1748 	else if (*ra)
1749 		SCSI_HBA_LOG((_LOG_NF(CONT),
1750 		    "?%s%d at %s%d: unit-address %s: %s",
1751 		    ddi_driver_name(child), ddi_get_instance(child),
1752 		    ddi_driver_name(self), ddi_get_instance(self), ua, ra));
1753 	else
1754 		SCSI_HBA_LOG((_LOG_NF(CONT),
1755 		    "?%s%d at %s%d: unit-address %s",
1756 		    ddi_driver_name(child), ddi_get_instance(child),
1757 		    ddi_driver_name(self), ddi_get_instance(self), ua));
1758 
1759 	return (DDI_SUCCESS);
1760 }
1761 
1762 
1763 /*
1764  * scsi_busctl_initchild is called to initialize the SCSA transport for
1765  * communication with a particular child scsi target device. Successful
1766  * initialization requires properties on the node which describe the address
1767  * of the target device. If the address of the target device can't be
1768  * determined from properties then DDI_NOT_WELL_FORMED is returned. Nodes that
1769  * are DDI_NOT_WELL_FORMED are considered an implementation artifact and
1770  * are hidden from devinfo snapshots by calling ndi_devi_set_hidden().
1771  * The child may be one of the following types of devinfo nodes:
1772  *
1773  * OBP node:
1774  *	OBP does not enumerate target devices attached a SCSI bus. These
1775  *	template/stub/wild-card nodes are a legacy artifact for support of old
1776  *	driver loading methods. Since they have no properties,
1777  *	DDI_NOT_WELL_FORMED will be returned.
1778  *
1779  * SID node:
1780  *	The node may be either a:
1781  *	    o	probe/barrier SID node
1782  *	    o	a dynamic SID target node
1783  *
1784  * driver.conf node: The situation for this nexus is different than most.
1785  *	Typically a driver.conf node definition is used to either define a
1786  *	new child devinfo node or to further decorate (via merge) a SID
1787  *	child with properties. In our case we use the nodes for *both*
1788  *	purposes.
1789  *
1790  * In both the SID node and driver.conf node cases we must form the nodes
1791  * "@addr" from the well-known scsi(9P) device unit-address properties on
1792  * the node.
1793  *
1794  * For HBA drivers that implement the deprecated tran_get_name interface,
1795  * "@addr" construction involves having that driver interpret properties via
1796  * scsi_busctl_ua -> scsi_ua_get -> tran_get_name: there is no
1797  * requirement for the property names to be well-known.
1798  *
1799  * NOTE: We don't currently support "merge".  When this support is added a
1800  * specific property, like "unit-address", should *always* identify a
1801  * driver.conf node that needs to be merged into a specific SID node. When
1802  * enumeration is enabled, a .conf node without the "unit-address" property
1803  * should be ignored.  The best way to establish the "unit-address" property
1804  * would be to have the system assign parent= and unit-address= from an
1805  * instance=# driver.conf entry (by using the instance tree).
1806  */
1807 static int
1808 scsi_busctl_initchild(dev_info_t *child)
1809 {
1810 	dev_info_t		*self = ddi_get_parent(child);
1811 	dev_info_t		*dup;
1812 	scsi_hba_tran_t		*tran;
1813 	struct scsi_device	*sd;
1814 	scsi_hba_tran_t		*tran_clone;
1815 	char			*class;
1816 	int			tgt;
1817 	int			lun;
1818 	int			sfunc;
1819 	int			err = DDI_FAILURE;
1820 	char			addr[SCSI_MAXNAMELEN];
1821 
1822 	ASSERT(DEVI_BUSY_OWNED(self));
1823 	SCSI_HBA_LOG((_LOG(4), NULL, child, "init begin"));
1824 
1825 	/*
1826 	 * For a driver like fp with multiple upper-layer-protocols
1827 	 * it is possible for scsi_hba_init in _init to plumb SCSA
1828 	 * and have the load of fcp (which does scsi_hba_attach_setup)
1829 	 * to fail.  In this case we may get here with a NULL hba.
1830 	 */
1831 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1832 	if (tran == NULL)
1833 		return (DDI_NOT_WELL_FORMED);
1834 
1835 	/*
1836 	 * OBP may create template/stub/wild-card nodes for legacy driver
1837 	 * loading methods. These nodes have no properties, so we lack the
1838 	 * addressing properties to initchild them. Hide the node and return
1839 	 * DDI_NOT_WELL_FORMED.
1840 	 *
1841 	 * Future: define/use a ndi_devi_has_properties(dip) type interface.
1842 	 *
1843 	 * NOTE: It would be nice if we could delete these ill formed nodes by
1844 	 * implementing a DDI_NOT_WELL_FORMED_DELETE return code. This can't
1845 	 * be done until leadville debug code removes its dependencies
1846 	 * on the devinfo still being present after a failed ndi_devi_online.
1847 	 */
1848 	if ((DEVI(child)->devi_hw_prop_ptr == NULL) &&
1849 	    (DEVI(child)->devi_drv_prop_ptr == NULL) &&
1850 	    (DEVI(child)->devi_sys_prop_ptr == NULL)) {
1851 		SCSI_HBA_LOG((_LOG(4), NULL, child,
1852 		    "init failed: no properties"));
1853 		ndi_devi_set_hidden(child);
1854 		return (DDI_NOT_WELL_FORMED);
1855 	}
1856 
1857 	/* get legacy SPI addressing properties */
1858 	if ((tgt = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1859 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1860 	    SCSI_ADDR_PROP_TARGET, -1)) == -1) {
1861 		tgt = 0;
1862 		/*
1863 		 * A driver.conf node for merging always has a target= property,
1864 		 * even if it is just a dummy that does not contain the real
1865 		 * target address. However drivers that register devids may
1866 		 * create stub driver.conf nodes without a target= property so
1867 		 * that pathological devid resolution works. Hide the stub
1868 		 * node and return DDI_NOT_WELL_FORMED.
1869 		 */
1870 		if (!scsi_hba_dev_is_sid(child)) {
1871 			SCSI_HBA_LOG((_LOG(4), NULL, child,
1872 			    "init failed: stub .conf node"));
1873 			ndi_devi_set_hidden(child);
1874 			return (DDI_NOT_WELL_FORMED);
1875 		}
1876 	}
1877 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1878 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, SCSI_ADDR_PROP_LUN, 0);
1879 	sfunc = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1880 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, SCSI_ADDR_PROP_SFUNC, -1);
1881 
1882 	/*
1883 	 * The scsi_address structure may not specify all the addressing
1884 	 * information. For an old HBA that doesn't support tran_get_name
1885 	 * (most pre-SCSI-3 HBAs) the scsi_address structure is still used,
1886 	 * so the target property must exist and the LUN must be < 256.
1887 	 */
1888 	if ((tran->tran_get_name == NULL) &&
1889 	    ((tgt >= USHRT_MAX) || (lun >= 256))) {
1890 		SCSI_HBA_LOG((_LOG(1), NULL, child,
1891 		    "init failed: illegal/missing properties"));
1892 		ndi_devi_set_hidden(child);
1893 		return (DDI_NOT_WELL_FORMED);
1894 	}
1895 
1896 	/*
1897 	 * We need to initialize a fair amount of our environment to invoke
1898 	 * tran_get_name (via scsi_busctl_ua and scsi_ua_get) to
1899 	 * produce the "@addr" name from addressing properties. Allocate and
1900 	 * initialize scsi device structure.
1901 	 */
1902 	sd = kmem_zalloc(sizeof (struct scsi_device), KM_SLEEP);
1903 	mutex_init(&sd->sd_mutex, NULL, MUTEX_DRIVER, NULL);
1904 	sd->sd_dev = child;
1905 	sd->sd_pathinfo = NULL;
1906 	sd->sd_uninit_prevent = 0;
1907 	ddi_set_driver_private(child, sd);
1908 
1909 	if (tran->tran_hba_flags & SCSI_HBA_ADDR_COMPLEX) {
1910 		/*
1911 		 * For a SCSI_HBA_ADDR_COMPLEX transport we store a pointer to
1912 		 * scsi_device in the scsi_address structure.  This allows an
1913 		 * HBA driver to find its per-scsi_device private data
1914 		 * (accessible to the HBA given just the scsi_address by using
1915 		 *  scsi_address_device(9F)/scsi_device_hba_private_get(9F)).
1916 		 */
1917 		sd->sd_address.a.a_sd = sd;
1918 		tran_clone = NULL;
1919 	} else {
1920 		/*
1921 		 * Initialize the scsi_address so that a SCSI-2 target driver
1922 		 * talking to a SCSI-2 device on a SCSI-3 bus (spi) continues
1923 		 * to work. We skew the secondary function value so that we
1924 		 * can tell from the address structure if we are processing
1925 		 * a secondary function request.
1926 		 */
1927 		sd->sd_address.a_target = (ushort_t)tgt;
1928 		sd->sd_address.a_lun = (uchar_t)lun;
1929 		if (sfunc == -1)
1930 			sd->sd_address.a_sublun = (uchar_t)0;
1931 		else
1932 			sd->sd_address.a_sublun = (uchar_t)sfunc + 1;
1933 
1934 		/*
1935 		 * NOTE: Don't limit LUNs to scsi_options value because a
1936 		 * scsi_device discovered via SPI dynamic enumeration might
1937 		 * still support SCMD_REPORT_LUNS.
1938 		 */
1939 
1940 		/*
1941 		 * Deprecated: Use SCSI_HBA_ADDR_COMPLEX:
1942 		 *   Clone transport structure if requested. Cloning allows
1943 		 *   an HBA to maintain target-specific information if
1944 		 *   necessary, such as target addressing information that
1945 		 *   does not adhere to the scsi_address structure format.
1946 		 */
1947 		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1948 			tran_clone = kmem_alloc(
1949 			    sizeof (scsi_hba_tran_t), KM_SLEEP);
1950 			bcopy((caddr_t)tran,
1951 			    (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
1952 			tran = tran_clone;
1953 			tran->tran_sd = sd;
1954 		} else {
1955 			tran_clone = NULL;
1956 			ASSERT(tran->tran_sd == NULL);
1957 		}
1958 	}
1959 
1960 	/* establish scsi_address pointer to the HBA's tran structure */
1961 	sd->sd_address.a_hba_tran = tran;
1962 
1963 	/*
1964 	 * This is a grotty hack that allows direct-access (non-scsa) drivers
1965 	 * (like chs, ata, and mlx which all make cmdk children) to put its
1966 	 * own vector in the 'a_hba_tran' field. When all the drivers that do
1967 	 * this are fixed, please remove this hack.
1968 	 *
1969 	 * NOTE: This hack is also shows up in the DEVP_TO_TRAN implementation
1970 	 * in scsi_confsubr.c.
1971 	 */
1972 	sd->sd_tran_safe = tran;
1973 
1974 	/*
1975 	 * If the class property is not already established, set it to "scsi".
1976 	 * This is done so that parent= driver.conf nodes have class.
1977 	 */
1978 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1979 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "class",
1980 	    &class) == DDI_PROP_SUCCESS) {
1981 		ddi_prop_free(class);
1982 	} else if (ndi_prop_update_string(DDI_DEV_T_NONE, child,
1983 	    "class", "scsi") != DDI_PROP_SUCCESS) {
1984 		SCSI_HBA_LOG((_LOG(2), NULL, child, "init failed: class"));
1985 		ndi_devi_set_hidden(child);
1986 		err = DDI_NOT_WELL_FORMED;
1987 		goto failure;
1988 	}
1989 
1990 	/* Establish the @addr name of the child. */
1991 	*addr = '\0';
1992 	if (scsi_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS) {
1993 		/*
1994 		 * Some driver.conf files add bogus target properties (relative
1995 		 * to their nexus representation of target) to their stub
1996 		 * nodes, causing the check above to not filter them.
1997 		 */
1998 		SCSI_HBA_LOG((_LOG(3), NULL, child,
1999 		    "init failed: scsi_busctl_ua call"));
2000 		ndi_devi_set_hidden(child);
2001 		err = DDI_NOT_WELL_FORMED;
2002 		goto failure;
2003 	}
2004 	if (*addr == '\0') {
2005 		SCSI_HBA_LOG((_LOG(2), NULL, child, "init failed: ua"));
2006 		ndi_devi_set_hidden(child);
2007 		err = DDI_NOT_WELL_FORMED;
2008 		goto failure;
2009 	}
2010 
2011 	/* Prevent duplicate nodes.  */
2012 	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
2013 	    scsi_busctl_ua);
2014 	if (dup) {
2015 		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_SCSI_DEVICE);
2016 		if (ndi_flavor_get(dup) != SCSA_FLAVOR_SCSI_DEVICE) {
2017 			SCSI_HBA_LOG((_LOG(1), NULL, child,
2018 			    "init failed: %s@%s: not SCSI_DEVICE flavored",
2019 			    ddi_node_name(child), addr));
2020 			goto failure;
2021 		}
2022 		if (dup != child) {
2023 			SCSI_HBA_LOG((_LOG(4), NULL, child,
2024 			    "init failed: %s@%s: detected duplicate %p",
2025 			    ddi_node_name(child), addr, (void *)dup));
2026 			goto failure;
2027 		}
2028 	}
2029 
2030 	/* set the node @addr string */
2031 	ddi_set_name_addr(child, addr);
2032 
2033 	/* call HBA's target init entry point if it exists */
2034 	if (tran->tran_tgt_init != NULL) {
2035 		SCSI_HBA_LOG((_LOG(4), NULL, child, "init tran_tgt_init"));
2036 
2037 		if ((*tran->tran_tgt_init)
2038 		    (self, child, tran, sd) != DDI_SUCCESS) {
2039 			if (ndi_dev_is_hotplug_node(child))
2040 				SCSI_HBA_LOG((_LOG(WARN), NULL, child,
2041 				    "enumeration failed during tran_tgt_init"));
2042 			else
2043 				SCSI_HBA_LOG((_LOG(2), NULL, child,
2044 				    "enumeration failed during tran_tgt_init"));
2045 			goto failure;
2046 		}
2047 	}
2048 
2049 	SCSI_HBA_LOG((_LOG(3), NULL, child, "init successful"));
2050 	return (DDI_SUCCESS);
2051 
2052 failure:
2053 	if (tran_clone)
2054 		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
2055 	mutex_destroy(&sd->sd_mutex);
2056 	kmem_free(sd, sizeof (*sd));
2057 	ddi_set_driver_private(child, NULL);
2058 	ddi_set_name_addr(child, NULL);
2059 
2060 	return (err);		/* remove the node */
2061 }
2062 
2063 static int
2064 scsi_busctl_uninitchild(dev_info_t *child)
2065 {
2066 	dev_info_t		*self = ddi_get_parent(child);
2067 	struct scsi_device	*sd = ddi_get_driver_private(child);
2068 	scsi_hba_tran_t		*tran;
2069 	scsi_hba_tran_t		*tran_clone;
2070 
2071 	ASSERT(DEVI_BUSY_OWNED(self));
2072 
2073 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
2074 	ASSERT(tran && sd);
2075 	if ((tran == NULL) || (sd == NULL))
2076 		return (DDI_FAILURE);
2077 
2078 	/*
2079 	 * We use sd_uninit_prevent to avoid uninitializing barrier/probe
2080 	 * nodes that are still in use. Since barrier/probe nodes are not
2081 	 * attached we can't prevent their state demotion via ndi_hold_devi.
2082 	 */
2083 	if (sd->sd_uninit_prevent) {
2084 		SCSI_HBA_LOG((_LOG(2), NULL, child, "uninit prevented"));
2085 		return (DDI_FAILURE);
2086 	}
2087 
2088 	/*
2089 	 * Don't uninitialize a client node if it still has paths.
2090 	 */
2091 	if (MDI_CLIENT(child) && mdi_client_get_path_count(child)) {
2092 		SCSI_HBA_LOG((_LOG(2), NULL, child,
2093 		    "uninit prevented, client has paths"));
2094 		return (DDI_FAILURE);
2095 	}
2096 
2097 	SCSI_HBA_LOG((_LOG(3), NULL, child, "uninit begin"));
2098 
2099 	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
2100 		tran_clone = sd->sd_address.a_hba_tran;
2101 
2102 		/* ... grotty hack, involving sd_tran_safe, continued. */
2103 		if (tran_clone != sd->sd_tran_safe) {
2104 			tran_clone = sd->sd_tran_safe;
2105 #ifdef	DEBUG
2106 			/*
2107 			 * Complain so things get fixed and hack can, at
2108 			 * some point in time, be removed.
2109 			 */
2110 			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2111 			    "'%s' is corrupting a_hba_tran", sd->sd_dev ?
2112 			    ddi_driver_name(sd->sd_dev) : "unknown_driver"));
2113 #endif	/* DEBUG */
2114 		}
2115 
2116 		ASSERT(tran_clone->tran_hba_flags & SCSI_HBA_TRAN_CLONE);
2117 		ASSERT(tran_clone->tran_sd == sd);
2118 		tran = tran_clone;
2119 	} else {
2120 		tran_clone = NULL;
2121 		ASSERT(tran->tran_sd == NULL);
2122 	}
2123 
2124 	/*
2125 	 * To simplify host adapter drivers we guarantee that multiple
2126 	 * tran_tgt_init(9E) calls of the same unit address are never
2127 	 * active at the same time.  This requires that we call
2128 	 * tran_tgt_free on probe/barrier nodes directly prior to
2129 	 * uninitchild.
2130 	 *
2131 	 * NOTE: To correctly support SCSI_HBA_TRAN_CLONE, we must use
2132 	 * the (possibly cloned) hba_tran pointer from the scsi_device
2133 	 * instead of hba_tran.
2134 	 */
2135 	if (tran->tran_tgt_free) {
2136 		if (!scsi_hba_devi_is_barrier(child)) {
2137 			SCSI_HBA_LOG((_LOG(4), NULL, child,
2138 			    "uninit tran_tgt_free"));
2139 
2140 			(*tran->tran_tgt_free) (self, child, tran, sd);
2141 		} else {
2142 			SCSI_HBA_LOG((_LOG(4), NULL, child,
2143 			    "uninit tran_tgt_free already done"));
2144 		}
2145 	}
2146 
2147 	/*
2148 	 * If a inquiry data is still allocated (by scsi_probe()) we
2149 	 * free the allocation here. This keeps scsi_inq valid for the
2150 	 * same duration as the corresponding inquiry properties. It
2151 	 * also allows a tran_tgt_init() implementation that establishes
2152 	 * sd_inq to deal with deallocation in its tran_tgt_free
2153 	 * (setting sd_inq back to NULL) without upsetting the
2154 	 * framework. Moving the inquiry free here also allows setting
2155 	 * of sd_uninit_prevent to preserve the data for lun0 based
2156 	 * scsi_get_device_type_scsi_options() calls.
2157 	 */
2158 	if (sd->sd_inq) {
2159 		kmem_free(sd->sd_inq, SUN_INQSIZE);
2160 		sd->sd_inq = (struct scsi_inquiry *)NULL;
2161 	}
2162 
2163 	mutex_destroy(&sd->sd_mutex);
2164 	if (tran_clone)
2165 		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
2166 	kmem_free(sd, sizeof (*sd));
2167 
2168 	ddi_set_driver_private(child, NULL);
2169 	SCSI_HBA_LOG((_LOG(3), NULL, child, "uninit complete"));
2170 	ddi_set_name_addr(child, NULL);
2171 	return (DDI_SUCCESS);
2172 }
2173 
2174 static int
2175 iport_busctl_ua(dev_info_t *child, char *addr, int maxlen)
2176 {
2177 	char	*iport_ua;
2178 
2179 	/* limit ndi_devi_findchild_by_callback to expected flavor */
2180 	if (ndi_flavor_get(child) != SCSA_FLAVOR_IPORT)
2181 		return (DDI_FAILURE);
2182 
2183 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2184 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2185 	    SCSI_ADDR_PROP_IPORTUA, &iport_ua) != DDI_SUCCESS) {
2186 		return (DDI_FAILURE);
2187 	}
2188 
2189 	(void) snprintf(addr, maxlen, "%s", iport_ua);
2190 	ddi_prop_free(iport_ua);
2191 	return (DDI_SUCCESS);
2192 }
2193 
2194 static int
2195 iport_busctl_reportdev(dev_info_t *child)
2196 {
2197 	dev_info_t	*self = ddi_get_parent(child);
2198 	char		*iport_ua;
2199 	char		*initiator_port = NULL;
2200 
2201 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2202 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2203 	    SCSI_ADDR_PROP_IPORTUA, &iport_ua) != DDI_SUCCESS)
2204 		return (DDI_FAILURE);
2205 
2206 	(void) ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2207 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2208 	    SCSI_ADDR_PROP_INITIATOR_PORT, &initiator_port);
2209 
2210 	if (initiator_port) {
2211 		SCSI_HBA_LOG((_LOG_NF(CONT),
2212 		    "?%s%d at %s%d: %s %s %s %s",
2213 		    ddi_driver_name(child), ddi_get_instance(child),
2214 		    ddi_driver_name(self), ddi_get_instance(self),
2215 		    SCSI_ADDR_PROP_INITIATOR_PORT, initiator_port,
2216 		    SCSI_ADDR_PROP_IPORTUA, iport_ua));
2217 		ddi_prop_free(initiator_port);
2218 	} else {
2219 		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: %s %s",
2220 		    ddi_driver_name(child), ddi_get_instance(child),
2221 		    ddi_driver_name(self), ddi_get_instance(self),
2222 		    SCSI_ADDR_PROP_IPORTUA, iport_ua));
2223 	}
2224 	ddi_prop_free(iport_ua);
2225 	return (DDI_SUCCESS);
2226 }
2227 
2228 /* initchild SCSA iport 'child' node */
2229 static int
2230 iport_busctl_initchild(dev_info_t *child)
2231 {
2232 	dev_info_t	*self = ddi_get_parent(child);
2233 	dev_info_t	*dup = NULL;
2234 	char		addr[SCSI_MAXNAMELEN];
2235 
2236 	if (iport_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS)
2237 		return (DDI_NOT_WELL_FORMED);
2238 
2239 	/* Prevent duplicate nodes.  */
2240 	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
2241 	    iport_busctl_ua);
2242 	if (dup) {
2243 		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_IPORT);
2244 		if (ndi_flavor_get(dup) != SCSA_FLAVOR_IPORT) {
2245 			SCSI_HBA_LOG((_LOG(1), NULL, child,
2246 			    "init failed: %s@%s: not IPORT flavored",
2247 			    ddi_node_name(child), addr));
2248 			return (DDI_FAILURE);
2249 		}
2250 		if (dup != child) {
2251 			SCSI_HBA_LOG((_LOG(4), NULL, child,
2252 			    "init failed: %s@%s: detected duplicate %p",
2253 			    ddi_node_name(child), addr, (void *)dup));
2254 			return (DDI_FAILURE);
2255 		}
2256 	}
2257 
2258 	/* set the node @addr string */
2259 	ddi_set_name_addr(child, addr);
2260 
2261 	return (DDI_SUCCESS);
2262 }
2263 
2264 /* uninitchild SCSA iport 'child' node */
2265 static int
2266 iport_busctl_uninitchild(dev_info_t *child)
2267 {
2268 	ddi_set_name_addr(child, NULL);
2269 	return (DDI_SUCCESS);
2270 }
2271 
2272 /* Uninitialize scsi_device flavor of transport on SCSA iport 'child' node. */
2273 static void
2274 iport_postdetach_tran_scsi_device(dev_info_t *child)
2275 {
2276 	scsi_hba_tran_t		*tran;
2277 
2278 	tran = ndi_flavorv_get(child, SCSA_FLAVOR_SCSI_DEVICE);
2279 	if (tran == NULL)
2280 		return;
2281 
2282 	scsa_tran_teardown(child, tran);
2283 	scsa_nexus_teardown(child, tran);
2284 
2285 	ndi_flavorv_set(child, SCSA_FLAVOR_SCSI_DEVICE, NULL);
2286 	scsi_hba_tran_free(tran);
2287 }
2288 
2289 /* Initialize scsi_device flavor of transport on SCSA iport 'child' node. */
2290 static void
2291 iport_preattach_tran_scsi_device(dev_info_t *child)
2292 {
2293 	dev_info_t	*hba = ddi_get_parent(child);
2294 	scsi_hba_tran_t	*htran;
2295 	scsi_hba_tran_t	*tran;
2296 
2297 	/* parent HBA node scsi_device tran is required */
2298 	htran = ndi_flavorv_get(hba, SCSA_FLAVOR_SCSI_DEVICE);
2299 	ASSERT(htran);
2300 
2301 	/* Allocate iport child's scsi_device transport vector */
2302 	tran = scsi_hba_tran_alloc(child, SCSI_HBA_CANSLEEP);
2303 	ASSERT(tran);
2304 
2305 	/* Structure-copy scsi_device transport of HBA to iport. */
2306 	*tran = *htran;
2307 
2308 	/*
2309 	 * Reset scsi_device transport fields not shared with the
2310 	 * parent, and not established below.
2311 	 */
2312 	tran->tran_open_flag = 0;
2313 	tran->tran_hba_private = NULL;
2314 
2315 	/* Establish the devinfo context of this tran structure. */
2316 	tran->tran_iport_dip = child;
2317 
2318 	/* Clear SCSI_HBA_SCSA flags (except TA) */
2319 	tran->tran_hba_flags &=
2320 	    ~(SCSI_HBA_SCSA_FM | SCSI_HBA_SCSA_PHCI);	/* clear parent state */
2321 	tran->tran_hba_flags |= SCSI_HBA_SCSA_TA;	/* always TA */
2322 	tran->tran_hba_flags &= ~SCSI_HBA_HBA;		/* never HBA */
2323 
2324 	/* Establish flavor of transport (and ddi_get_driver_private()) */
2325 	ndi_flavorv_set(child, SCSA_FLAVOR_SCSI_DEVICE, tran);
2326 
2327 	/* Setup iport node */
2328 	if ((scsa_nexus_setup(child, tran) != DDI_SUCCESS) ||
2329 	    (scsa_tran_setup(child, tran) != DDI_SUCCESS))
2330 		iport_postdetach_tran_scsi_device(child);
2331 }
2332 
2333 /* Uninitialize smp_device flavor of transport on SCSA iport 'child' node. */
2334 static void
2335 iport_postdetach_tran_smp_device(dev_info_t *child)
2336 {
2337 	smp_hba_tran_t	*tran;
2338 
2339 	tran = ndi_flavorv_get(child, SCSA_FLAVOR_SMP);
2340 	if (tran == NULL)
2341 		return;
2342 
2343 	ndi_flavorv_set(child, SCSA_FLAVOR_SMP, NULL);
2344 	smp_hba_tran_free(tran);
2345 }
2346 
2347 /* Initialize smp_device flavor of transport on SCSA iport 'child' node. */
2348 static void
2349 iport_preattach_tran_smp_device(dev_info_t *child)
2350 {
2351 	dev_info_t	*hba = ddi_get_parent(child);
2352 	smp_hba_tran_t	*htran;
2353 	smp_hba_tran_t	*tran;
2354 
2355 	/* parent HBA node smp_device tran is optional */
2356 	htran = ndi_flavorv_get(hba, SCSA_FLAVOR_SMP);
2357 	if (htran == NULL) {
2358 		ndi_flavorv_set(child, SCSA_FLAVOR_SMP, NULL);
2359 		return;
2360 	}
2361 
2362 	/* Allocate iport child's smp_device transport vector */
2363 	tran = smp_hba_tran_alloc(child);
2364 
2365 	/* Structure-copy smp_device transport of HBA to iport. */
2366 	*tran = *htran;
2367 
2368 	/* Establish flavor of transport */
2369 	ndi_flavorv_set(child, SCSA_FLAVOR_SMP, tran);
2370 }
2371 
2372 /*
2373  * Generic bus_ctl operations for SCSI HBA's,
2374  * hiding the busctl interface from the HBA.
2375  */
2376 /*ARGSUSED*/
2377 static int
2378 scsi_hba_bus_ctl(
2379 	dev_info_t		*self,
2380 	dev_info_t		*child,
2381 	ddi_ctl_enum_t		op,
2382 	void			*arg,
2383 	void			*result)
2384 {
2385 	int			child_flavor = 0;
2386 	int			val;
2387 	ddi_dma_attr_t		*attr;
2388 	scsi_hba_tran_t		*tran;
2389 	struct attachspec	*as;
2390 	struct detachspec	*ds;
2391 
2392 	/* For some ops, child is 'arg'. */
2393 	if ((op == DDI_CTLOPS_INITCHILD) || (op == DDI_CTLOPS_UNINITCHILD))
2394 		child = (dev_info_t *)arg;
2395 
2396 	/* Determine the flavor of the child: scsi, smp, iport */
2397 	child_flavor = ndi_flavor_get(child);
2398 
2399 	switch (op) {
2400 	case DDI_CTLOPS_INITCHILD:
2401 		switch (child_flavor) {
2402 		case SCSA_FLAVOR_SCSI_DEVICE:
2403 			return (scsi_busctl_initchild(child));
2404 		case SCSA_FLAVOR_SMP:
2405 			return (smp_busctl_initchild(child));
2406 		case SCSA_FLAVOR_IPORT:
2407 			return (iport_busctl_initchild(child));
2408 		default:
2409 			return (DDI_FAILURE);
2410 		}
2411 		/* NOTREACHED */
2412 
2413 	case DDI_CTLOPS_UNINITCHILD:
2414 		switch (child_flavor) {
2415 		case SCSA_FLAVOR_SCSI_DEVICE:
2416 			return (scsi_busctl_uninitchild(child));
2417 		case SCSA_FLAVOR_SMP:
2418 			return (smp_busctl_uninitchild(child));
2419 		case SCSA_FLAVOR_IPORT:
2420 			return (iport_busctl_uninitchild(child));
2421 		default:
2422 			return (DDI_FAILURE);
2423 		}
2424 		/* NOTREACHED */
2425 
2426 	case DDI_CTLOPS_REPORTDEV:
2427 		switch (child_flavor) {
2428 		case SCSA_FLAVOR_SCSI_DEVICE:
2429 			return (scsi_busctl_reportdev(child));
2430 		case SCSA_FLAVOR_SMP:
2431 			return (smp_busctl_reportdev(child));
2432 		case SCSA_FLAVOR_IPORT:
2433 			return (iport_busctl_reportdev(child));
2434 		default:
2435 			return (DDI_FAILURE);
2436 		}
2437 		/* NOTREACHED */
2438 
2439 	case DDI_CTLOPS_ATTACH:
2440 		as = (struct attachspec *)arg;
2441 
2442 		if (child_flavor != SCSA_FLAVOR_IPORT)
2443 			return (DDI_SUCCESS);
2444 
2445 		/* iport processing */
2446 		if (as->when == DDI_PRE) {
2447 			/* setup pre attach(9E) */
2448 			iport_preattach_tran_scsi_device(child);
2449 			iport_preattach_tran_smp_device(child);
2450 		} else if ((as->when == DDI_POST) &&
2451 		    (as->result != DDI_SUCCESS)) {
2452 			/* cleanup if attach(9E) failed */
2453 			iport_postdetach_tran_scsi_device(child);
2454 			iport_postdetach_tran_smp_device(child);
2455 		}
2456 		return (DDI_SUCCESS);
2457 
2458 	case DDI_CTLOPS_DETACH:
2459 		ds = (struct detachspec *)arg;
2460 
2461 		if (child_flavor != SCSA_FLAVOR_IPORT)
2462 			return (DDI_SUCCESS);
2463 
2464 		/* iport processing */
2465 		if ((ds->when == DDI_POST) &&
2466 		    (ds->result == DDI_SUCCESS)) {
2467 			/* cleanup if detach(9E) was successful */
2468 			iport_postdetach_tran_scsi_device(child);
2469 			iport_postdetach_tran_smp_device(child);
2470 		}
2471 		return (DDI_SUCCESS);
2472 
2473 	case DDI_CTLOPS_IOMIN:
2474 		tran = ddi_get_driver_private(self);
2475 		ASSERT(tran);
2476 		if (tran == NULL)
2477 			return (DDI_FAILURE);
2478 
2479 		/*
2480 		 * The 'arg' value of nonzero indicates 'streaming'
2481 		 * mode. If in streaming mode, pick the largest
2482 		 * of our burstsizes available and say that that
2483 		 * is our minimum value (modulo what minxfer is).
2484 		 */
2485 		attr = &tran->tran_dma_attr;
2486 		val = *((int *)result);
2487 		val = maxbit(val, attr->dma_attr_minxfer);
2488 		*((int *)result) = maxbit(val, ((intptr_t)arg ?
2489 		    (1<<ddi_ffs(attr->dma_attr_burstsizes)-1) :
2490 		    (1<<(ddi_fls(attr->dma_attr_burstsizes)-1))));
2491 
2492 		return (ddi_ctlops(self, child, op, arg, result));
2493 
2494 	case DDI_CTLOPS_SIDDEV:
2495 		return (ndi_dev_is_persistent_node(child) ?
2496 		    DDI_SUCCESS : DDI_FAILURE);
2497 
2498 	case DDI_CTLOPS_POWER:
2499 		return (DDI_SUCCESS);
2500 
2501 	/*
2502 	 * These ops correspond to functions that "shouldn't" be called
2503 	 * by a SCSI target driver. So we whine when we're called.
2504 	 */
2505 	case DDI_CTLOPS_DMAPMAPC:
2506 	case DDI_CTLOPS_REPORTINT:
2507 	case DDI_CTLOPS_REGSIZE:
2508 	case DDI_CTLOPS_NREGS:
2509 	case DDI_CTLOPS_SLAVEONLY:
2510 	case DDI_CTLOPS_AFFINITY:
2511 	case DDI_CTLOPS_POKE:
2512 	case DDI_CTLOPS_PEEK:
2513 		SCSI_HBA_LOG((_LOG(WARN), self, NULL, "invalid op (%d)", op));
2514 		return (DDI_FAILURE);
2515 
2516 	/* Everything else we pass up */
2517 	case DDI_CTLOPS_PTOB:
2518 	case DDI_CTLOPS_BTOP:
2519 	case DDI_CTLOPS_BTOPR:
2520 	case DDI_CTLOPS_DVMAPAGESIZE:
2521 	default:
2522 		return (ddi_ctlops(self, child, op, arg, result));
2523 	}
2524 	/* NOTREACHED */
2525 }
2526 
2527 /*
2528  * Private wrapper for scsi_pkt's allocated via scsi_hba_pkt_alloc()
2529  */
2530 struct scsi_pkt_wrapper {
2531 	struct scsi_pkt		scsi_pkt;
2532 	int			pkt_wrapper_magic;
2533 	int			pkt_wrapper_len;
2534 };
2535 
2536 #if !defined(lint)
2537 _NOTE(SCHEME_PROTECTS_DATA("unique per thread", scsi_pkt_wrapper))
2538 _NOTE(SCHEME_PROTECTS_DATA("Unshared Data", dev_ops))
2539 #endif
2540 
2541 /*
2542  * Called by an HBA to allocate a scsi_pkt
2543  */
2544 /*ARGSUSED*/
2545 struct scsi_pkt *
2546 scsi_hba_pkt_alloc(
2547 	dev_info_t		*self,
2548 	struct scsi_address	*ap,
2549 	int			cmdlen,
2550 	int			statuslen,
2551 	int			tgtlen,
2552 	int			hbalen,
2553 	int			(*callback)(caddr_t arg),
2554 	caddr_t			arg)
2555 {
2556 	struct scsi_pkt		*pkt;
2557 	struct scsi_pkt_wrapper	*hba_pkt;
2558 	caddr_t			p;
2559 	int			acmdlen, astatuslen, atgtlen, ahbalen;
2560 	int			pktlen;
2561 
2562 	/* Sanity check */
2563 	if (callback != SLEEP_FUNC && callback != NULL_FUNC)
2564 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2565 		    "callback must be SLEEP_FUNC or NULL_FUNC"));
2566 
2567 	/*
2568 	 * Round up so everything gets allocated on long-word boundaries
2569 	 */
2570 	acmdlen = ROUNDUP(cmdlen);
2571 	astatuslen = ROUNDUP(statuslen);
2572 	atgtlen = ROUNDUP(tgtlen);
2573 	ahbalen = ROUNDUP(hbalen);
2574 	pktlen = sizeof (struct scsi_pkt_wrapper) +
2575 	    acmdlen + astatuslen + atgtlen + ahbalen;
2576 
2577 	hba_pkt = kmem_zalloc(pktlen,
2578 	    (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP);
2579 	if (hba_pkt == NULL) {
2580 		ASSERT(callback == NULL_FUNC);
2581 		return (NULL);
2582 	}
2583 
2584 	/*
2585 	 * Set up our private info on this pkt
2586 	 */
2587 	hba_pkt->pkt_wrapper_len = pktlen;
2588 	hba_pkt->pkt_wrapper_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
2589 	pkt = &hba_pkt->scsi_pkt;
2590 
2591 	/*
2592 	 * Set up pointers to private data areas, cdb, and status.
2593 	 */
2594 	p = (caddr_t)(hba_pkt + 1);
2595 	if (hbalen > 0) {
2596 		pkt->pkt_ha_private = (opaque_t)p;
2597 		p += ahbalen;
2598 	}
2599 	if (tgtlen > 0) {
2600 		pkt->pkt_private = (opaque_t)p;
2601 		p += atgtlen;
2602 	}
2603 	if (statuslen > 0) {
2604 		pkt->pkt_scbp = (uchar_t *)p;
2605 		p += astatuslen;
2606 	}
2607 	if (cmdlen > 0) {
2608 		pkt->pkt_cdbp = (uchar_t *)p;
2609 	}
2610 
2611 	/*
2612 	 * Initialize the pkt's scsi_address
2613 	 */
2614 	pkt->pkt_address = *ap;
2615 
2616 	/*
2617 	 * NB: It may not be safe for drivers, esp target drivers, to depend
2618 	 * on the following fields being set until all the scsi_pkt
2619 	 * allocation violations discussed in scsi_pkt.h are all resolved.
2620 	 */
2621 	pkt->pkt_cdblen = cmdlen;
2622 	pkt->pkt_tgtlen = tgtlen;
2623 	pkt->pkt_scblen = statuslen;
2624 
2625 	return (pkt);
2626 }
2627 
2628 /*
2629  * Called by an HBA to free a scsi_pkt
2630  */
2631 /*ARGSUSED*/
2632 void
2633 scsi_hba_pkt_free(
2634 	struct scsi_address	*ap,
2635 	struct scsi_pkt		*pkt)
2636 {
2637 	kmem_free(pkt, ((struct scsi_pkt_wrapper *)pkt)->pkt_wrapper_len);
2638 }
2639 
2640 /*
2641  * Return 1 if the scsi_pkt used a proper allocator.
2642  *
2643  * The DDI does not allow a driver to allocate it's own scsi_pkt(9S), a
2644  * driver should not have *any* compiled in dependencies on "sizeof (struct
2645  * scsi_pkt)". While this has been the case for many years, a number of
2646  * drivers have still not been fixed. This function can be used to detect
2647  * improperly allocated scsi_pkt structures, and produce messages identifying
2648  * drivers that need to be fixed.
2649  *
2650  * While drivers in violation are being fixed, this function can also
2651  * be used by the framework to detect packets that violated allocation
2652  * rules.
2653  *
2654  * NB: It is possible, but very unlikely, for this code to return a false
2655  * positive (finding correct magic, but for wrong reasons).  Careful
2656  * consideration is needed for callers using this interface to condition
2657  * access to newer scsi_pkt fields (those after pkt_reason).
2658  *
2659  * NB: As an aid to minimizing the amount of work involved in 'fixing' legacy
2660  * drivers that violate scsi_*(9S) allocation rules, private
2661  * scsi_pkt_size()/scsi_size_clean() functions are available (see their
2662  * implementation for details).
2663  *
2664  * *** Non-legacy use of scsi_pkt_size() is discouraged. ***
2665  *
2666  * NB: When supporting broken HBA drivers is not longer a concern, this
2667  * code should be removed.
2668  */
2669 int
2670 scsi_pkt_allocated_correctly(struct scsi_pkt *pkt)
2671 {
2672 	struct scsi_pkt_wrapper	*hba_pkt = (struct scsi_pkt_wrapper *)pkt;
2673 	int	magic;
2674 	major_t	major;
2675 #ifdef	DEBUG
2676 	int	*pspwm, *pspcwm;
2677 
2678 	/*
2679 	 * We are getting scsi packets from two 'correct' wrapper schemes,
2680 	 * make sure we are looking at the same place in both to detect
2681 	 * proper allocation.
2682 	 */
2683 	pspwm = &((struct scsi_pkt_wrapper *)0)->pkt_wrapper_magic;
2684 	pspcwm = &((struct scsi_pkt_cache_wrapper *)0)->pcw_magic;
2685 	ASSERT(pspwm == pspcwm);
2686 #endif	/* DEBUG */
2687 
2688 
2689 	/*
2690 	 * Check to see if driver is scsi_size_clean(), assume it
2691 	 * is using the scsi_pkt_size() interface everywhere it needs to
2692 	 * if the driver indicates it is scsi_size_clean().
2693 	 */
2694 	major = ddi_driver_major(P_TO_TRAN(pkt)->tran_hba_dip);
2695 	if (devnamesp[major].dn_flags & DN_SCSI_SIZE_CLEAN)
2696 		return (1);		/* ok */
2697 
2698 	/*
2699 	 * Special case crossing a page boundary. If the scsi_pkt was not
2700 	 * allocated correctly, then across a page boundary we have a
2701 	 * fault hazard.
2702 	 */
2703 	if ((((uintptr_t)(&hba_pkt->scsi_pkt)) & MMU_PAGEMASK) ==
2704 	    (((uintptr_t)(&hba_pkt->pkt_wrapper_magic)) & MMU_PAGEMASK)) {
2705 		/* fastpath, no cross-page hazard */
2706 		magic = hba_pkt->pkt_wrapper_magic;
2707 	} else {
2708 		/* add protection for cross-page hazard */
2709 		if (ddi_peek32((dev_info_t *)NULL,
2710 		    &hba_pkt->pkt_wrapper_magic, &magic) == DDI_FAILURE) {
2711 			return (0);	/* violation */
2712 		}
2713 	}
2714 
2715 	/* properly allocated packet always has correct magic */
2716 	return ((magic == PKT_WRAPPER_MAGIC) ? 1 : 0);
2717 }
2718 
2719 /*
2720  * Private interfaces to simplify conversion of legacy drivers so they don't
2721  * depend on scsi_*(9S) size. Instead of using these private interface, HBA
2722  * drivers should use DDI sanctioned allocation methods:
2723  *
2724  *	scsi_pkt	Use scsi_hba_pkt_alloc(9F), or implement
2725  *			tran_setup_pkt(9E).
2726  *
2727  *	scsi_device	You are doing something strange/special, a scsi_device
2728  *			structure should only be allocated by scsi_hba.c
2729  *			initchild code or scsi_vhci.c code.
2730  *
2731  *	scsi_hba_tran	Use scsi_hba_tran_alloc(9F).
2732  */
2733 size_t
2734 scsi_pkt_size()
2735 {
2736 	return (sizeof (struct scsi_pkt));
2737 }
2738 
2739 size_t
2740 scsi_hba_tran_size()
2741 {
2742 	return (sizeof (scsi_hba_tran_t));
2743 }
2744 
2745 size_t
2746 scsi_device_size()
2747 {
2748 	return (sizeof (struct scsi_device));
2749 }
2750 
2751 /*
2752  * Legacy compliance to scsi_pkt(9S) allocation rules through use of
2753  * scsi_pkt_size() is detected by the 'scsi-size-clean' driver.conf property
2754  * or an HBA driver calling to scsi_size_clean() from attach(9E).  A driver
2755  * developer should only indicate that a legacy driver is clean after using
2756  * SCSI_SIZE_CLEAN_VERIFY to ensure compliance (see scsi_pkt.h).
2757  */
2758 void
2759 scsi_size_clean(dev_info_t *self)
2760 {
2761 	major_t		major;
2762 	struct devnames	*dnp;
2763 
2764 	ASSERT(self);
2765 	major = ddi_driver_major(self);
2766 	ASSERT(major < devcnt);
2767 	if (major >= devcnt) {
2768 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2769 		    "scsi_pkt_size: bogus major: %d", major));
2770 		return;
2771 	}
2772 
2773 	/* Set DN_SCSI_SIZE_CLEAN flag in dn_flags. */
2774 	dnp = &devnamesp[major];
2775 	if ((dnp->dn_flags & DN_SCSI_SIZE_CLEAN) == 0) {
2776 		LOCK_DEV_OPS(&dnp->dn_lock);
2777 		dnp->dn_flags |= DN_SCSI_SIZE_CLEAN;
2778 		UNLOCK_DEV_OPS(&dnp->dn_lock);
2779 	}
2780 }
2781 
2782 
2783 /*
2784  * Called by an HBA to map strings to capability indices
2785  */
2786 int
2787 scsi_hba_lookup_capstr(
2788 	char			*capstr)
2789 {
2790 	/*
2791 	 * Capability strings: only add entries to mask the legacy
2792 	 * '_' vs. '-' misery.  All new capabilities should use '-',
2793 	 * and be captured be added to SCSI_CAP_ASCII.
2794 	 */
2795 	static struct cap_strings {
2796 		char	*cap_string;
2797 		int	cap_index;
2798 	} cap_strings[] = {
2799 		{ "dma_max",		SCSI_CAP_DMA_MAX		},
2800 		{ "msg_out",		SCSI_CAP_MSG_OUT		},
2801 		{ "wide_xfer",		SCSI_CAP_WIDE_XFER		},
2802 		{ NULL,			0				}
2803 	};
2804 	static char		*cap_ascii[] = SCSI_CAP_ASCII;
2805 	char			**cap;
2806 	int			i;
2807 	struct cap_strings	*cp;
2808 
2809 	for (cap = cap_ascii, i = 0; *cap != NULL; cap++, i++)
2810 		if (strcmp(*cap, capstr) == 0)
2811 			return (i);
2812 
2813 	for (cp = cap_strings; cp->cap_string != NULL; cp++)
2814 		if (strcmp(cp->cap_string, capstr) == 0)
2815 			return (cp->cap_index);
2816 
2817 	return (-1);
2818 }
2819 
2820 /*
2821  * Called by an HBA to determine if the system is in 'panic' state.
2822  */
2823 int
2824 scsi_hba_in_panic()
2825 {
2826 	return (panicstr != NULL);
2827 }
2828 
2829 /*
2830  * If a SCSI target driver attempts to mmap memory,
2831  * the buck stops here.
2832  */
2833 /*ARGSUSED*/
2834 static int
2835 scsi_hba_map_fault(
2836 	dev_info_t		*self,
2837 	dev_info_t		*child,
2838 	struct hat		*hat,
2839 	struct seg		*seg,
2840 	caddr_t			addr,
2841 	struct devpage		*dp,
2842 	pfn_t			pfn,
2843 	uint_t			prot,
2844 	uint_t			lock)
2845 {
2846 	return (DDI_FAILURE);
2847 }
2848 
2849 static int
2850 scsi_hba_get_eventcookie(
2851 	dev_info_t		*self,
2852 	dev_info_t		*child,
2853 	char			*name,
2854 	ddi_eventcookie_t	*eventp)
2855 {
2856 	scsi_hba_tran_t		*tran;
2857 
2858 	tran = ddi_get_driver_private(self);
2859 	if (tran->tran_get_eventcookie &&
2860 	    ((*tran->tran_get_eventcookie)(self,
2861 	    child, name, eventp) == DDI_SUCCESS)) {
2862 		return (DDI_SUCCESS);
2863 	}
2864 
2865 	return (ndi_busop_get_eventcookie(self, child, name, eventp));
2866 }
2867 
2868 static int
2869 scsi_hba_add_eventcall(
2870 	dev_info_t		*self,
2871 	dev_info_t		*child,
2872 	ddi_eventcookie_t	event,
2873 	void			(*callback)(
2874 					dev_info_t *self,
2875 					ddi_eventcookie_t event,
2876 					void *arg,
2877 					void *bus_impldata),
2878 	void			*arg,
2879 	ddi_callback_id_t	*cb_id)
2880 {
2881 	scsi_hba_tran_t		*tran;
2882 
2883 	tran = ddi_get_driver_private(self);
2884 	if (tran->tran_add_eventcall &&
2885 	    ((*tran->tran_add_eventcall)(self, child,
2886 	    event, callback, arg, cb_id) == DDI_SUCCESS)) {
2887 		return (DDI_SUCCESS);
2888 	}
2889 
2890 	return (DDI_FAILURE);
2891 }
2892 
2893 static int
2894 scsi_hba_remove_eventcall(dev_info_t *self, ddi_callback_id_t cb_id)
2895 {
2896 	scsi_hba_tran_t		*tran;
2897 	ASSERT(cb_id);
2898 
2899 	tran = ddi_get_driver_private(self);
2900 	if (tran->tran_remove_eventcall &&
2901 	    ((*tran->tran_remove_eventcall)(
2902 	    self, cb_id) == DDI_SUCCESS)) {
2903 		return (DDI_SUCCESS);
2904 	}
2905 
2906 	return (DDI_FAILURE);
2907 }
2908 
2909 static int
2910 scsi_hba_post_event(
2911 	dev_info_t		*self,
2912 	dev_info_t		*child,
2913 	ddi_eventcookie_t	event,
2914 	void			*bus_impldata)
2915 {
2916 	scsi_hba_tran_t		*tran;
2917 
2918 	tran = ddi_get_driver_private(self);
2919 	if (tran->tran_post_event &&
2920 	    ((*tran->tran_post_event)(self,
2921 	    child, event, bus_impldata) == DDI_SUCCESS)) {
2922 		return (DDI_SUCCESS);
2923 	}
2924 
2925 	return (DDI_FAILURE);
2926 }
2927 
2928 /*
2929  * Default getinfo(9e) for scsi_hba
2930  */
2931 /* ARGSUSED */
2932 static int
2933 scsi_hba_info(dev_info_t *self, ddi_info_cmd_t infocmd, void *arg,
2934     void **result)
2935 {
2936 	int error = DDI_SUCCESS;
2937 
2938 	switch (infocmd) {
2939 	case DDI_INFO_DEVT2INSTANCE:
2940 		*result = (void *)(intptr_t)(MINOR2INST(getminor((dev_t)arg)));
2941 		break;
2942 	default:
2943 		error = DDI_FAILURE;
2944 	}
2945 	return (error);
2946 }
2947 
2948 /*
2949  * Default open and close routine for scsi_hba
2950  */
2951 /* ARGSUSED */
2952 int
2953 scsi_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
2954 {
2955 	dev_info_t	*self;
2956 	scsi_hba_tran_t	*tran;
2957 	int		rv = 0;
2958 
2959 	if (otyp != OTYP_CHR)
2960 		return (EINVAL);
2961 
2962 	if ((self = e_ddi_hold_devi_by_dev(*devp, 0)) == NULL)
2963 		return (ENXIO);
2964 
2965 	tran = ddi_get_driver_private(self);
2966 	if (tran == NULL) {
2967 		ddi_release_devi(self);
2968 		return (ENXIO);
2969 	}
2970 
2971 	/*
2972 	 * tran_open_flag bit field:
2973 	 *	0:	closed
2974 	 *	1:	shared open by minor at bit position
2975 	 *	1 at 31st bit:	exclusive open
2976 	 */
2977 	mutex_enter(&(tran->tran_open_lock));
2978 	if (flags & FEXCL) {
2979 		if (tran->tran_open_flag != 0) {
2980 			rv = EBUSY;		/* already open */
2981 		} else {
2982 			tran->tran_open_flag = TRAN_OPEN_EXCL;
2983 		}
2984 	} else {
2985 		if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
2986 			rv = EBUSY;		/* already excl. open */
2987 		} else {
2988 			int minor = getminor(*devp) & TRAN_MINOR_MASK;
2989 			tran->tran_open_flag |= (1 << minor);
2990 			/*
2991 			 * Ensure that the last framework reserved minor
2992 			 * is unused. Otherwise, the exclusive open
2993 			 * mechanism may break.
2994 			 */
2995 			ASSERT(minor != 31);
2996 		}
2997 	}
2998 	mutex_exit(&(tran->tran_open_lock));
2999 
3000 	ddi_release_devi(self);
3001 	return (rv);
3002 }
3003 
3004 /* ARGSUSED */
3005 int
3006 scsi_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
3007 {
3008 	dev_info_t	*self;
3009 	scsi_hba_tran_t	*tran;
3010 
3011 	if (otyp != OTYP_CHR)
3012 		return (EINVAL);
3013 
3014 	if ((self = e_ddi_hold_devi_by_dev(dev, 0)) == NULL)
3015 		return (ENXIO);
3016 
3017 	tran = ddi_get_driver_private(self);
3018 	if (tran == NULL) {
3019 		ddi_release_devi(self);
3020 		return (ENXIO);
3021 	}
3022 
3023 	mutex_enter(&(tran->tran_open_lock));
3024 	if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
3025 		tran->tran_open_flag = 0;
3026 	} else {
3027 		int minor = getminor(dev) & TRAN_MINOR_MASK;
3028 		tran->tran_open_flag &= ~(1 << minor);
3029 	}
3030 	mutex_exit(&(tran->tran_open_lock));
3031 
3032 	ddi_release_devi(self);
3033 	return (0);
3034 }
3035 
3036 /*
3037  * standard ioctl commands for SCSI hotplugging
3038  */
3039 /* ARGSUSED */
3040 int
3041 scsi_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
3042     int *rvalp)
3043 {
3044 	dev_info_t		*self;
3045 	struct devctl_iocdata	*dcp = NULL;
3046 	dev_info_t		*child = NULL;
3047 	mdi_pathinfo_t		*path = NULL;
3048 	struct scsi_device	*sd;
3049 	scsi_hba_tran_t		*tran;
3050 	uint_t			bus_state;
3051 	int			rv = 0;
3052 	int			circ;
3053 	char			*name;
3054 	char			*addr;
3055 
3056 	self = e_ddi_hold_devi_by_dev(dev, 0);
3057 	if (self == NULL) {
3058 		rv = ENXIO;
3059 		goto out;
3060 	}
3061 
3062 	tran = ddi_get_driver_private(self);
3063 	if (tran == NULL) {
3064 		rv = ENXIO;
3065 		goto out;
3066 	}
3067 
3068 	/* Ioctls for which the generic implementation suffices. */
3069 	switch (cmd) {
3070 	case DEVCTL_BUS_GETSTATE:
3071 		rv = ndi_devctl_ioctl(self, cmd, arg, mode, 0);
3072 		goto out;
3073 	}
3074 
3075 	/* read devctl ioctl data */
3076 	if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS) {
3077 		rv = EFAULT;
3078 		goto out;
3079 	}
3080 
3081 	/* Ioctls that require child identification */
3082 	switch (cmd) {
3083 	case DEVCTL_DEVICE_GETSTATE:
3084 	case DEVCTL_DEVICE_ONLINE:
3085 	case DEVCTL_DEVICE_OFFLINE:
3086 	case DEVCTL_DEVICE_REMOVE:
3087 	case DEVCTL_DEVICE_RESET:
3088 		name = ndi_dc_getname(dcp);
3089 		addr = ndi_dc_getaddr(dcp);
3090 		if ((name == NULL) || (addr == NULL)) {
3091 			rv = EINVAL;
3092 			goto out;
3093 		}
3094 
3095 		/*
3096 		 * Find child with name@addr - might find a devinfo
3097 		 * child (child), a pathinfo child (path), or nothing.
3098 		 */
3099 		scsi_hba_devi_enter(self, &circ);
3100 
3101 		(void) scsi_hba_find_child(self, name, addr,
3102 		    1, &child, &path, NULL);
3103 		if (path) {
3104 			/* Found a pathinfo */
3105 			ASSERT(path && (child == NULL));
3106 			mdi_hold_path(path);
3107 			scsi_hba_devi_exit_phci(self, circ);
3108 			sd = NULL;
3109 		} else if (child) {
3110 			/* Found a devinfo */
3111 			ASSERT(child && (path == NULL));
3112 
3113 			/* verify scsi_device of child */
3114 			if (ndi_flavor_get(child) == SCSA_FLAVOR_SCSI_DEVICE)
3115 				sd = ddi_get_driver_private(child);
3116 			else
3117 				sd = NULL;
3118 		} else {
3119 			ASSERT((path == NULL) && (child == NULL));
3120 			scsi_hba_devi_exit(self, circ);
3121 			rv = ENXIO;			/* found nothing */
3122 			goto out;
3123 		}
3124 		break;
3125 
3126 	case DEVCTL_BUS_RESETALL:	/* ioctl that operate on any child */
3127 		/*
3128 		 * Find a child's scsi_address so we can invoke tran_reset.
3129 		 *
3130 		 * Future: If no child exists, we could fake a child. This will
3131 		 * be a enhancement for the future - for now, we fall back to
3132 		 * BUS_RESET.
3133 		 */
3134 		scsi_hba_devi_enter(self, &circ);
3135 		child = ddi_get_child(self);
3136 		sd = NULL;
3137 		while (child) {
3138 			/* verify scsi_device of child */
3139 			if (ndi_flavor_get(child) == SCSA_FLAVOR_SCSI_DEVICE)
3140 				sd = ddi_get_driver_private(child);
3141 			if (sd != NULL) {
3142 				/*
3143 				 * NOTE: node has a scsi_device structure, so
3144 				 * it must be initialized.
3145 				 */
3146 				ndi_hold_devi(child);
3147 				break;
3148 			}
3149 			child = ddi_get_next_sibling(child);
3150 		}
3151 		scsi_hba_devi_exit(self, circ);
3152 		break;
3153 	}
3154 
3155 	switch (cmd) {
3156 	case DEVCTL_DEVICE_GETSTATE:
3157 		if (path) {
3158 			if (mdi_dc_return_dev_state(path, dcp) != MDI_SUCCESS)
3159 				rv = EFAULT;
3160 		} else if (child) {
3161 			if (ndi_dc_return_dev_state(child, dcp) != NDI_SUCCESS)
3162 				rv = EFAULT;
3163 		} else {
3164 			rv = ENXIO;
3165 		}
3166 		break;
3167 
3168 	case DEVCTL_DEVICE_RESET:
3169 		if (sd == NULL) {
3170 			rv = ENOTTY;
3171 			break;
3172 		}
3173 		if (tran->tran_reset == NULL) {
3174 			rv = ENOTSUP;
3175 			break;
3176 		}
3177 
3178 		/* Start with the small stick */
3179 		if (scsi_reset(&sd->sd_address, RESET_LUN) == 1)
3180 			break;		/* LUN reset worked */
3181 		if (scsi_reset(&sd->sd_address, RESET_TARGET) != 1)
3182 			rv = EIO;	/* Target reset failed */
3183 		break;
3184 
3185 	case DEVCTL_BUS_QUIESCE:
3186 		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
3187 		    (bus_state == BUS_QUIESCED))
3188 			rv = EALREADY;
3189 		else if (tran->tran_quiesce == NULL)
3190 			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3191 		else if (tran->tran_quiesce(self) != 0)
3192 			rv = EIO;
3193 		else if (ndi_set_bus_state(self, BUS_QUIESCED) != NDI_SUCCESS)
3194 			rv = EIO;
3195 		break;
3196 
3197 	case DEVCTL_BUS_UNQUIESCE:
3198 		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
3199 		    (bus_state == BUS_ACTIVE))
3200 			rv = EALREADY;
3201 		else if (tran->tran_unquiesce == NULL)
3202 			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3203 		else if (tran->tran_unquiesce(self) != 0)
3204 			rv = EIO;
3205 		else if (ndi_set_bus_state(self, BUS_ACTIVE) != NDI_SUCCESS)
3206 			rv = EIO;
3207 		break;
3208 
3209 	case DEVCTL_BUS_RESET:
3210 		if (tran->tran_bus_reset == NULL)
3211 			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3212 		else if (tran->tran_bus_reset(self, RESET_BUS) != 1)
3213 			rv = EIO;
3214 		break;
3215 
3216 	case DEVCTL_BUS_RESETALL:
3217 		if ((sd != NULL) &&
3218 		    (scsi_reset(&sd->sd_address, RESET_ALL) == 1)) {
3219 			break;		/* reset all worked */
3220 		}
3221 		if (tran->tran_bus_reset == NULL) {
3222 			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3223 			break;
3224 		}
3225 		if (tran->tran_bus_reset(self, RESET_BUS) != 1)
3226 			rv = EIO;	/* bus reset failed */
3227 		break;
3228 
3229 	case DEVCTL_BUS_CONFIGURE:
3230 		if (ndi_devi_config(self, NDI_DEVFS_CLEAN | NDI_DEVI_PERSIST |
3231 		    NDI_CONFIG_REPROBE) != NDI_SUCCESS) {
3232 			rv = EIO;
3233 		}
3234 		break;
3235 
3236 	case DEVCTL_BUS_UNCONFIGURE:
3237 		if (ndi_devi_unconfig(self,
3238 		    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) != NDI_SUCCESS) {
3239 			rv = EBUSY;
3240 		}
3241 		break;
3242 
3243 	case DEVCTL_DEVICE_ONLINE:
3244 		ASSERT(child || path);
3245 		if (path) {
3246 			if (mdi_pi_online(path, NDI_USER_REQ) != MDI_SUCCESS)
3247 				rv = EIO;
3248 		} else {
3249 			if (ndi_devi_online(child, 0) != NDI_SUCCESS)
3250 				rv = EIO;
3251 		}
3252 		break;
3253 
3254 	case DEVCTL_DEVICE_OFFLINE:
3255 		ASSERT(child || path);
3256 		if (sd != NULL)
3257 			(void) scsi_clear_task_set(&sd->sd_address);
3258 		if (path) {
3259 			if (mdi_pi_offline(path, NDI_USER_REQ) != MDI_SUCCESS)
3260 				rv = EIO;
3261 		} else {
3262 			if (ndi_devi_offline(child,
3263 			    NDI_DEVFS_CLEAN) != NDI_SUCCESS)
3264 				rv = EIO;
3265 		}
3266 		break;
3267 
3268 	case DEVCTL_DEVICE_REMOVE:
3269 		ASSERT(child || path);
3270 		if (sd != NULL)
3271 			(void) scsi_clear_task_set(&sd->sd_address);
3272 		if (path) {
3273 			/* NOTE: don't pass NDI_DEVI_REMOVE to mdi_pi_offline */
3274 			if (mdi_pi_offline(path, NDI_USER_REQ) == MDI_SUCCESS) {
3275 				scsi_hba_devi_enter_phci(self, &circ);
3276 				mdi_rele_path(path);
3277 
3278 				/* ... here is the DEVICE_REMOVE part. */
3279 				(void) mdi_pi_free(path, 0);
3280 				path = NULL;
3281 			} else {
3282 				rv = EIO;
3283 			}
3284 		} else {
3285 			if (ndi_devi_offline(child,
3286 			    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) != NDI_SUCCESS)
3287 				rv = EIO;
3288 		}
3289 		break;
3290 
3291 	default:
3292 		ASSERT(dcp != NULL);
3293 		rv = ENOTTY;
3294 		break;
3295 	}
3296 
3297 	/* all done -- clean up and return */
3298 out:
3299 	/* release hold on what we found */
3300 	if (path) {
3301 		scsi_hba_devi_enter_phci(self, &circ);
3302 		mdi_rele_path(path);
3303 	}
3304 	if (path || child)
3305 		scsi_hba_devi_exit(self, circ);
3306 
3307 	if (dcp)
3308 		ndi_dc_freehdl(dcp);
3309 
3310 	if (self)
3311 		ddi_release_devi(self);
3312 
3313 	*rvalp = rv;
3314 
3315 	return (rv);
3316 }
3317 
3318 /*ARGSUSED*/
3319 static int
3320 scsi_hba_fm_init_child(dev_info_t *self, dev_info_t *child, int cap,
3321     ddi_iblock_cookie_t *ibc)
3322 {
3323 	scsi_hba_tran_t	*tran = ddi_get_driver_private(self);
3324 
3325 	return (tran ? tran->tran_fm_capable : scsi_fm_capable);
3326 }
3327 
3328 static int
3329 scsi_hba_bus_power(dev_info_t *self, void *impl_arg, pm_bus_power_op_t op,
3330     void *arg, void *result)
3331 {
3332 	scsi_hba_tran_t	*tran;
3333 
3334 	tran = ddi_get_driver_private(self);
3335 	if (tran && tran->tran_bus_power) {
3336 		return (tran->tran_bus_power(self, impl_arg,
3337 		    op, arg, result));
3338 	}
3339 
3340 	return (pm_busop_bus_power(self, impl_arg, op, arg, result));
3341 }
3342 
3343 /*
3344  * Return the lun64 value from a address string: "addr,lun[,sfunc]". Either
3345  * the lun is after the first ',' or the entire address string is the lun.
3346  * Return SCSI_LUN64_ILLEGAL if the format is incorrect. A lun64 is at most
3347  * 16 hex digits long.
3348  *
3349  * If the address string specified has incorrect syntax (busconfig one of
3350  * bogus /devices path) then scsi_addr_to_lun64 can return SCSI_LUN64_ILLEGAL.
3351  */
3352 static scsi_lun64_t
3353 scsi_addr_to_lun64(char *addr)
3354 {
3355 	scsi_lun64_t	lun64;
3356 	char		*s;
3357 	int		i;
3358 
3359 	if (addr) {
3360 		s = strchr(addr, ',');			/* "addr,lun" */
3361 		if (s)
3362 			s++;				/* skip ',', at lun */
3363 		else
3364 			s = addr;			/* "lun" */
3365 
3366 		for (lun64 = 0, i = 0; *s && (i < 16); s++, i++) {
3367 			if (*s >= '0' && *s <= '9')
3368 				lun64 = (lun64 << 4) + (*s - '0');
3369 			else if (*s >= 'A' && *s <= 'F')
3370 				lun64 = (lun64 << 4) + 10 + (*s - 'A');
3371 			else if (*s >= 'a' && *s <= 'f')
3372 				lun64 = (lun64 << 4) + 10 + (*s - 'a');
3373 			else
3374 				break;
3375 		}
3376 		if (*s && (*s != ','))		/* [,sfunc] is OK */
3377 			lun64 = SCSI_LUN64_ILLEGAL;
3378 	} else
3379 		lun64 = SCSI_LUN64_ILLEGAL;
3380 
3381 	if (lun64 == SCSI_LUN64_ILLEGAL)
3382 		SCSI_HBA_LOG((_LOG(2), NULL, NULL,
3383 		    "addr_to_lun64 %s lun %" PRIlun64,
3384 		    addr ? addr : "NULL", lun64));
3385 	return (lun64);
3386 }
3387 
3388 /*
3389  * Return the sfunc value from a address string: "addr,lun[,sfunc]". Either the
3390  * sfunc is after the second ',' or the entire address string is the sfunc.
3391  * Return -1 if there is only one ',' in the address string or the string is
3392  * invalid. An sfunc is at most two hex digits long.
3393  */
3394 static int
3395 scsi_addr_to_sfunc(char *addr)
3396 {
3397 	int		sfunc;
3398 	char		*s;
3399 	int		i;
3400 
3401 	if (addr) {
3402 		s = strchr(addr, ',');			/* "addr,lun" */
3403 		if (s) {
3404 			s++;				/* skip ',', at lun */
3405 			s = strchr(s, ',');		/* "lun,sfunc]" */
3406 			if (s == NULL)
3407 				return (-1);		/* no ",sfunc" */
3408 			s++;				/* skip ',', at sfunc */
3409 		} else
3410 			s = addr;			/* "sfunc" */
3411 
3412 		for (sfunc = 0, i = 0; *s && (i < 2); s++, i++) {
3413 			if (*s >= '0' && *s <= '9')
3414 				sfunc = (sfunc << 4) + (*s - '0');
3415 			else if (*s >= 'A' && *s <= 'F')
3416 				sfunc = (sfunc << 4) + 10 + (*s - 'A');
3417 			else if (*s >= 'a' && *s <= 'f')
3418 				sfunc = (sfunc << 4) + 10 + (*s - 'a');
3419 			else
3420 				break;
3421 		}
3422 		if (*s)
3423 			sfunc = -1;			/* illegal */
3424 	} else
3425 		sfunc = -1;
3426 	return (sfunc);
3427 }
3428 
3429 /*
3430  * Convert scsi ascii string data to NULL terminated (semi) legal IEEE 1275
3431  * "compatible" (name) property form.
3432  *
3433  * For ASCII INQUIRY data, a one-way conversion algorithm is needed to take
3434  * SCSI_ASCII (20h - 7Eh) to a 1275-like compatible form. The 1275 spec allows
3435  * letters, digits, one ",", and ". _ + -", all limited by a maximum 31
3436  * character length. Since ", ." are used as separators in the compatible
3437  * string itself, they are converted to "_". All SCSI_ASCII characters that
3438  * are illegal in 1275, as well as any illegal SCSI_ASCII characters
3439  * encountered, are converted to "_". To reduce length, trailing blanks are
3440  * trimmed from SCSI_ASCII fields prior to conversion.
3441  *
3442  * Example: SCSI_ASCII "ST32550W SUN2.1G" -> "ST32550W_SUN2_1G"
3443  *
3444  * NOTE: the 1275 string form is always less than or equal to the scsi form.
3445  */
3446 static char *
3447 string_scsi_to_1275(char *s_1275, char *s_scsi, int len)
3448 {
3449 	(void) strncpy(s_1275, s_scsi, len);
3450 	s_1275[len--] = '\0';
3451 
3452 	while (len >= 0) {
3453 		if (s_1275[len] == ' ')
3454 			s_1275[len--] = '\0';	/* trim trailing " " */
3455 		else
3456 			break;
3457 	}
3458 
3459 	while (len >= 0) {
3460 		if (((s_1275[len] >= 'a') && (s_1275[len] <= 'z')) ||
3461 		    ((s_1275[len] >= 'A') && (s_1275[len] <= 'Z')) ||
3462 		    ((s_1275[len] >= '0') && (s_1275[len] <= '9')) ||
3463 		    (s_1275[len] == '_') ||
3464 		    (s_1275[len] == '+') ||
3465 		    (s_1275[len] == '-'))
3466 			len--;			/* legal 1275  */
3467 		else
3468 			s_1275[len--] = '_';	/* illegal SCSI_ASCII | 1275 */
3469 	}
3470 
3471 	return (s_1275);
3472 }
3473 
3474 /*
3475  * Given the inquiry data, binding_set, and dtype_node for a scsi device,
3476  * return the nodename and compatible property for the device. The "compatible"
3477  * concept comes from IEEE-1275. The compatible information is returned is in
3478  * the correct form for direct use defining the "compatible" string array
3479  * property. Internally, "compatible" is also used to determine the nodename
3480  * to return.
3481  *
3482  * This function is provided as a separate entry point for use by drivers that
3483  * currently issue their own non-SCSA inquiry command and perform their own
3484  * node creation based their own private compiled in tables. Converting these
3485  * drivers to use this interface provides a quick easy way of obtaining
3486  * consistency as well as the flexibility associated with the 1275 techniques.
3487  *
3488  * The dtype_node is passed as a separate argument (instead of having the
3489  * implementation use inq_dtype). It indicates that information about
3490  * a secondary function embedded service should be produced.
3491  *
3492  * Callers must always use scsi_hba_nodename_compatible_free, even if
3493  * *nodenamep is null, to free the nodename and compatible information
3494  * when done.
3495  *
3496  * If a nodename can't be determined then **compatiblep will point to a
3497  * diagnostic string containing all the compatible forms.
3498  *
3499  * NOTE: some compatible strings may violate the 31 character restriction
3500  * imposed by IEEE-1275. This is not a problem because Solaris does not care
3501  * about this 31 character limit.
3502  *
3503  * Each compatible form belongs to a form-group.  The form-groups currently
3504  * defined are generic ("scsiclass"), binding-set ("scsa.b"), and failover
3505  * ("scsa.f").
3506  *
3507  * The following compatible forms, in high to low precedence
3508  * order, are defined for SCSI target device nodes.
3509  *
3510  *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(1 *1&2)
3511  *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(2 *1)
3512  *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(3 *2)
3513  *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(4)
3514  *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP	(5 *1&2)
3515  *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(6 *1)
3516  *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(7 *2)
3517  *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(8)
3518  *  scsa,DD.bBBBBBBBB					(8.5 *3)
3519  *  scsiclass,DDEEFFF					(9 *1&2)
3520  *  scsiclass,DDEE					(10 *1)
3521  *  scsiclass,DDFFF					(11 *2)
3522  *  scsiclass,DD					(12)
3523  *  scsa.fFFF						(12.5 *4)
3524  *  scsiclass						(13)
3525  *
3526  *	  *1 only produced on a secondary function node
3527  *	  *2 only produced when generic form-group flags exist.
3528  *	  *3 only produced when binding-set form-group legacy support is needed
3529  *	  *4 only produced when failover form-group flags exist.
3530  *
3531  *	where:
3532  *
3533  *	v			is the letter 'v'. Denotest the
3534  *				beginning of VVVVVVVV.
3535  *
3536  *	VVVVVVVV		Translated scsi_vendor.
3537  *
3538  *	p			is the letter 'p'. Denotes the
3539  *				beginning of PPPPPPPPPPPPPPPP.
3540  *
3541  *	PPPPPPPPPPPPPPPP	Translated scsi_product.
3542  *
3543  *	r			is the letter 'r'. Denotes the
3544  *				beginning of RRRR.
3545  *
3546  *	RRRR			Translated scsi_revision.
3547  *
3548  *	DD			is a two digit ASCII hexadecimal
3549  *				number. The value of the two digits is
3550  *				based one the SCSI "Peripheral device
3551  *				type" command set associated with the
3552  *				node. On a primary node this is the
3553  *				scsi_dtype of the primary command set,
3554  *				on a secondary node this is the
3555  *				scsi_dtype associated with the secondary
3556  *				function embedded command set.
3557  *
3558  *	EE			Same encoding used for DD. This form is
3559  *				only generated on secondary function
3560  *				nodes. The DD secondary function is embedded
3561  *				in an EE device.
3562  *
3563  *	FFF			Concatenation, in alphabetical order,
3564  *				of the flag characters within a form-group.
3565  *				For a given form-group, the following
3566  *				flags are defined.
3567  *
3568  *				scsiclass: (generic form-group):
3569  *				  R	Removable_Media: Used when
3570  *					inq_rmb is set.
3571  *				  S	SAF-TE device: Used when
3572  *					inquiry information indicates
3573  *					SAF-TE devices.
3574  *
3575  *				scsa.f:	(failover form-group):
3576  *				  E	Explicit Target_Port_Group: Used
3577  *					when inq_tpgse is set and 'G' is
3578  *					alse present.
3579  *				  G	GUID: Used when a GUID can be
3580  *					generated for the device.
3581  *				  I	Implicit Target_Port_Group: Used
3582  *					when inq_tpgs is set and 'G' is
3583  *					also present.
3584  *
3585  *				Forms using FFF are only be generated
3586  *				if there are applicable flag
3587  *				characters.
3588  *
3589  *	b			is the letter 'b'. Denotes the
3590  *				beginning of BBBBBBBB.
3591  *
3592  *	BBBBBBBB		Binding-set. Operating System Specific:
3593  *				scsi-binding-set property of HBA.
3594  */
3595 #define	NCOMPAT		(1 + (13 + 2) + 1)
3596 #define	COMPAT_LONGEST	(strlen( \
3597 	"scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR" + 1))
3598 
3599 /*
3600  * Private version with extra device 'identity' arguments to allow code
3601  * to determine GUID FFF support.
3602  */
3603 static void
3604 scsi_hba_ident_nodename_compatible_get(struct scsi_inquiry *inq,
3605     uchar_t *inq80, size_t inq80len, uchar_t *inq83, size_t inq83len,
3606     char *binding_set, int dtype_node, char *compat0,
3607     char **nodenamep, char **drivernamep,
3608     char ***compatiblep, int *ncompatiblep)
3609 {
3610 	char		vid[sizeof (inq->inq_vid) + 1 ];
3611 	char		pid[sizeof (inq->inq_pid) + 1];
3612 	char		rev[sizeof (inq->inq_revision) + 1];
3613 	char		gf[sizeof ("RS\0")];
3614 	char		ff[sizeof ("EGI\0")];
3615 	int		dtype_device;
3616 	int		ncompat;		/* number of compatible */
3617 	char		**compatp;		/* compatible ptrs */
3618 	int		i;
3619 	char		*nname;			/* nodename */
3620 	char		*dname;			/* driver name */
3621 	char		**csp;
3622 	char		*p;
3623 	int		tlen;
3624 	int		len;
3625 	major_t		major;
3626 	ddi_devid_t	devid;
3627 	char		*guid;
3628 	uchar_t		*iqd = (uchar_t *)inq;
3629 
3630 	/*
3631 	 * Nodename_aliases: This table was originally designed to be
3632 	 * implemented via a new nodename_aliases file - a peer to the
3633 	 * driver_aliases that selects a nodename based on compatible
3634 	 * forms in much the same say driver_aliases is used to select
3635 	 * driver bindings from compatible forms. Each compatible form
3636 	 * is an 'alias'. Until a more general need for a
3637 	 * nodename_aliases file exists, which may never occur, the
3638 	 * scsi mappings are described here via a compiled in table.
3639 	 *
3640 	 * This table contains nodename mappings for self-identifying
3641 	 * scsi devices enumerated by the Solaris kernel. For a given
3642 	 * device, the highest precedence "compatible" form with a
3643 	 * mapping is used to select the nodename for the device. This
3644 	 * will typically be a generic nodename, however in some legacy
3645 	 * compatibility cases a driver nodename mapping may be selected.
3646 	 *
3647 	 * Because of possible breakage associated with switching SCSI
3648 	 * target devices from driver nodenames to generic nodenames,
3649 	 * we are currently unable to support generic nodenames for all
3650 	 * SCSI devices (binding-sets). Although /devices paths are
3651 	 * defined as unstable, avoiding possible breakage is
3652 	 * important. Some of the newer SCSI transports (USB) already
3653 	 * use generic nodenames. All new SCSI transports and target
3654 	 * devices should use generic nodenames. At times this decision
3655 	 * may be architecture dependent (sparc .vs. intel) based on when
3656 	 * a transport was supported on a particular architecture.
3657 	 *
3658 	 * We provide a base set of generic nodename mappings based on
3659 	 * scsiclass dtype and higher-precedence driver nodename
3660 	 * mappings based on scsa "binding-set" to cover legacy
3661 	 * issues. The binding-set is typically associated with
3662 	 * "scsi-binding-set" property value of the HBA. The legacy
3663 	 * mappings are provided independent of whether the driver they
3664 	 * refer to is installed. This allows a correctly named node
3665 	 * be created at discovery time, and binding to occur when/if
3666 	 * an add_drv of the legacy driver occurs.
3667 	 *
3668 	 * We also have mappings for legacy SUN hardware that
3669 	 * misidentifies itself (enclosure services which identify
3670 	 * themselves as processors). All future hardware should use
3671 	 * the correct dtype.
3672 	 *
3673 	 * As SCSI HBAs are modified to use the SCSA interfaces for
3674 	 * self-identifying SCSI target devices (PSARC/2004/116) the
3675 	 * nodename_aliases table (PSARC/2004/420) should be augmented
3676 	 * with legacy mappings in order to maintain compatibility with
3677 	 * existing /devices paths, especially for devices that house
3678 	 * an OS. Failure to do this may cause upgrade problems.
3679 	 * Additions for new target devices or transports should not
3680 	 * add scsa binding-set compatible mappings.
3681 	 */
3682 	static struct nodename_aliases {
3683 		char	*na_nodename;		/* nodename */
3684 		char	*na_alias;		/* compatible form match */
3685 	} na[] = {
3686 	/* # mapping to generic nodenames based on scsi dtype */
3687 		{"disk",		"scsiclass,00"},
3688 		{"tape",		"scsiclass,01"},
3689 		{"printer",		"scsiclass,02"},
3690 		{"processor",		"scsiclass,03"},
3691 		{"worm",		"scsiclass,04"},
3692 		{"cdrom",		"scsiclass,05"},
3693 		{"scanner",		"scsiclass,06"},
3694 		{"optical-disk",	"scsiclass,07"},
3695 		{"medium-changer",	"scsiclass,08"},
3696 		{"obsolete",		"scsiclass,09"},
3697 		{"prepress-a",		"scsiclass,0a"},
3698 		{"prepress-b",		"scsiclass,0b"},
3699 		{"array-controller",	"scsiclass,0c"},
3700 		{"enclosure",		"scsiclass,0d"},
3701 		{"disk",		"scsiclass,0e"},
3702 		{"card-reader",		"scsiclass,0f"},
3703 		{"bridge",		"scsiclass,10"},
3704 		{"object-store",	"scsiclass,11"},
3705 		{"reserved",		"scsiclass,12"},
3706 		{"reserved",		"scsiclass,13"},
3707 		{"reserved",		"scsiclass,14"},
3708 		{"reserved",		"scsiclass,15"},
3709 		{"reserved",		"scsiclass,16"},
3710 		{"reserved",		"scsiclass,17"},
3711 		{"reserved",		"scsiclass,18"},
3712 		{"reserved",		"scsiclass,19"},
3713 		{"reserved",		"scsiclass,1a"},
3714 		{"reserved",		"scsiclass,1b"},
3715 		{"reserved",		"scsiclass,1c"},
3716 		{"reserved",		"scsiclass,1d"},
3717 		{"well-known-lun",	"scsiclass,1e"},
3718 		{"unknown",		"scsiclass,1f"},
3719 
3720 #ifdef	sparc
3721 	/* # legacy mapping to driver nodenames for fcp binding-set */
3722 		{"ssd",			"scsa,00.bfcp"},
3723 		{"st",			"scsa,01.bfcp"},
3724 		{"sgen",		"scsa,08.bfcp"},
3725 		{"ses",			"scsa,0d.bfcp"},
3726 
3727 	/* # legacy mapping to driver nodenames for vhci binding-set */
3728 		{"ssd",			"scsa,00.bvhci"},
3729 		{"st",			"scsa,01.bvhci"},
3730 		{"sgen",		"scsa,08.bvhci"},
3731 		{"ses",			"scsa,0d.bvhci"},
3732 #else	/* sparc */
3733 	/* # for x86 fcp and vhci use generic nodenames */
3734 #endif	/* sparc */
3735 
3736 	/* # legacy mapping to driver nodenames for spi binding-set */
3737 		{"sd",			"scsa,00.bspi"},
3738 		{"sd",			"scsa,05.bspi"},
3739 		{"sd",			"scsa,07.bspi"},
3740 		{"st",			"scsa,01.bspi"},
3741 		{"ses",			"scsa,0d.bspi"},
3742 
3743 	/* #				SUN misidentified spi hardware */
3744 		{"ses",			"scsiclass,03.vSUN.pD2"},
3745 		{"ses",			"scsiclass,03.vSYMBIOS.pD1000"},
3746 
3747 	/* # legacy mapping to driver nodenames for atapi binding-set */
3748 		{"sd",			"scsa,00.batapi"},
3749 		{"sd",			"scsa,05.batapi"},
3750 		{"sd",			"scsa,07.batapi"},
3751 		{"st",			"scsa,01.batapi"},
3752 		{"unknown",		"scsa,0d.batapi"},
3753 
3754 	/* # legacy mapping to generic nodenames for usb binding-set */
3755 		{"disk",		"scsa,05.busb"},
3756 		{"disk",		"scsa,07.busb"},
3757 		{"changer",		"scsa,08.busb"},
3758 		{"comm",		"scsa,09.busb"},
3759 		{"array_ctlr",		"scsa,0c.busb"},
3760 		{"esi",			"scsa,0d.busb"},
3761 
3762 	/*
3763 	 * mapping nodenames for mpt based on scsi dtype
3764 	 * for being compatible with the original node names
3765 	 * under mpt controller
3766 	 */
3767 		{"sd",			"scsa,00.bmpt"},
3768 		{"sd",			"scsa,05.bmpt"},
3769 		{"sd",			"scsa,07.bmpt"},
3770 		{"st",			"scsa,01.bmpt"},
3771 		{"ses",			"scsa,0d.bmpt"},
3772 		{"sgen",		"scsa,08.bmpt"},
3773 		{NULL,		NULL}
3774 	};
3775 	struct nodename_aliases *nap;
3776 
3777 	/* NOTE: drivernamep can be NULL */
3778 	ASSERT(nodenamep && compatiblep && ncompatiblep &&
3779 	    (binding_set == NULL || (strlen(binding_set) <= 8)));
3780 	if ((nodenamep == NULL) || (compatiblep == NULL) ||
3781 	    (ncompatiblep == NULL))
3782 		return;
3783 
3784 	/*
3785 	 * In order to reduce runtime we allocate one block of memory that
3786 	 * contains both the NULL terminated array of pointers to compatible
3787 	 * forms and the individual compatible strings. This block is
3788 	 * somewhat larger than needed, but is short lived - it only exists
3789 	 * until the caller can transfer the information into the "compatible"
3790 	 * string array property and call scsi_hba_nodename_compatible_free.
3791 	 */
3792 	tlen = NCOMPAT * COMPAT_LONGEST;
3793 	compatp = kmem_alloc((NCOMPAT * sizeof (char *)) + tlen, KM_SLEEP);
3794 
3795 	/* convert inquiry data from SCSI ASCII to 1275 string */
3796 	(void) string_scsi_to_1275(vid, inq->inq_vid,
3797 	    sizeof (inq->inq_vid));
3798 	(void) string_scsi_to_1275(pid, inq->inq_pid,
3799 	    sizeof (inq->inq_pid));
3800 	(void) string_scsi_to_1275(rev, inq->inq_revision,
3801 	    sizeof (inq->inq_revision));
3802 	ASSERT((strlen(vid) <= sizeof (inq->inq_vid)) &&
3803 	    (strlen(pid) <= sizeof (inq->inq_pid)) &&
3804 	    (strlen(rev) <= sizeof (inq->inq_revision)));
3805 
3806 	/*
3807 	 * Form flags in ***ALPHABETICAL*** order within form-group:
3808 	 *
3809 	 * NOTE: When adding a new flag to an existing form-group, careful
3810 	 * consideration must be given to not breaking existing bindings
3811 	 * based on that form-group.
3812 	 */
3813 
3814 	/*
3815 	 * generic form-group flags
3816 	 *   R	removable:
3817 	 *	Set when inq_rmb is set and for well known scsi dtypes. For a
3818 	 *	bus where the entire device is removable (like USB), we expect
3819 	 *	the HBA to intercept the inquiry data and set inq_rmb.
3820 	 *	Since OBP does not distinguish removable media in its generic
3821 	 *	name selection we avoid setting the 'R' flag if the root is not
3822 	 *	yet mounted.
3823 	 *   S	SAF-TE device
3824 	 *	Set when the device type is SAT-TE.
3825 	 */
3826 	i = 0;
3827 	dtype_device = inq->inq_dtype & DTYPE_MASK;
3828 	if (modrootloaded && (inq->inq_rmb ||
3829 	    (dtype_device == DTYPE_WORM) ||
3830 	    (dtype_device == DTYPE_RODIRECT) ||
3831 	    (dtype_device == DTYPE_OPTICAL)))
3832 		gf[i++] = 'R';			/* removable */
3833 	gf[i] = '\0';
3834 
3835 	if (modrootloaded &&
3836 	    (dtype_device == DTYPE_PROCESSOR) &&
3837 	    (strncmp((char *)&iqd[44], "SAF-TE", 4) == 0))
3838 		gf[i++] = 'S';
3839 	gf[i] = '\0';
3840 
3841 	/*
3842 	 * failover form-group flags
3843 	 *   E	Explicit Target_Port_Group_Supported:
3844 	 *	Set for a device that has a GUID if inq_tpgse also set.
3845 	 *   G	GUID:
3846 	 *	Set when we have identity information, can determine a devid
3847 	 *	from the identity information, and can generate a guid from
3848 	 *	that devid.
3849 	 *   I	Implicit Target_Port_Group_Supported:
3850 	 *	Set for a device that has a GUID if inq_tpgs also set.
3851 	 */
3852 	i = 0;
3853 	if ((inq80 || inq83) &&
3854 	    (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST, NULL,
3855 	    (uchar_t *)inq, sizeof (*inq), inq80, inq80len, inq83, inq83len,
3856 	    &devid) == DDI_SUCCESS)) {
3857 		guid = ddi_devid_to_guid(devid);
3858 		ddi_devid_free(devid);
3859 	} else
3860 		guid = NULL;
3861 	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_EXPLICIT))
3862 		ff[i++] = 'E';			/* EXPLICIT TPGS */
3863 	if (guid)
3864 		ff[i++] = 'G';			/* GUID */
3865 	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_IMPLICIT))
3866 		ff[i++] = 'I';			/* IMPLICIT TPGS */
3867 	ff[i] = '\0';
3868 	if (guid)
3869 		ddi_devid_free_guid(guid);
3870 
3871 	/*
3872 	 * Construct all applicable compatible forms. See comment at the
3873 	 * head of the function for a description of the compatible forms.
3874 	 */
3875 	csp = compatp;
3876 	p = (char *)(compatp + NCOMPAT);
3877 
3878 	/* ( 0) driver (optional, not documented in scsi(4)) */
3879 	if (compat0) {
3880 		*csp++ = p;
3881 		(void) snprintf(p, tlen, "%s", compat0);
3882 		len = strlen(p) + 1;
3883 		p += len;
3884 		tlen -= len;
3885 	}
3886 
3887 	/* ( 1) scsiclass,DDEEFFF.vV.pP.rR */
3888 	if ((dtype_device != dtype_node) && *gf && *vid && *pid && *rev) {
3889 		*csp++ = p;
3890 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s.r%s",
3891 		    dtype_node, dtype_device, gf, vid, pid, rev);
3892 		len = strlen(p) + 1;
3893 		p += len;
3894 		tlen -= len;
3895 	}
3896 
3897 	/* ( 2) scsiclass,DDEE.vV.pP.rR */
3898 	if ((dtype_device != dtype_node) && *vid && *pid && *rev) {
3899 		*csp++ = p;
3900 		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s.r%s",
3901 		    dtype_node, dtype_device, vid, pid, rev);
3902 		len = strlen(p) + 1;
3903 		p += len;
3904 		tlen -= len;
3905 	}
3906 
3907 	/* ( 3) scsiclass,DDFFF.vV.pP.rR */
3908 	if (*gf && *vid && *pid && *rev) {
3909 		*csp++ = p;
3910 		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s.r%s",
3911 		    dtype_node, gf, vid, pid, rev);
3912 		len = strlen(p) + 1;
3913 		p += len;
3914 		tlen -= len;
3915 	}
3916 
3917 	/* ( 4) scsiclass,DD.vV.pP.rR */
3918 	if (*vid && *pid && rev) {
3919 		*csp++ = p;
3920 		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s.r%s",
3921 		    dtype_node, vid, pid, rev);
3922 		len = strlen(p) + 1;
3923 		p += len;
3924 		tlen -= len;
3925 	}
3926 
3927 	/* ( 5) scsiclass,DDEEFFF.vV.pP */
3928 	if ((dtype_device != dtype_node) && *gf && *vid && *pid) {
3929 		*csp++ = p;
3930 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s",
3931 		    dtype_node, dtype_device, gf, vid, pid);
3932 		len = strlen(p) + 1;
3933 		p += len;
3934 		tlen -= len;
3935 	}
3936 
3937 	/* ( 6) scsiclass,DDEE.vV.pP */
3938 	if ((dtype_device != dtype_node) && *vid && *pid) {
3939 		*csp++ = p;
3940 		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s",
3941 		    dtype_node, dtype_device, vid, pid);
3942 		len = strlen(p) + 1;
3943 		p += len;
3944 		tlen -= len;
3945 	}
3946 
3947 	/* ( 7) scsiclass,DDFFF.vV.pP */
3948 	if (*gf && *vid && *pid) {
3949 		*csp++ = p;
3950 		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s",
3951 		    dtype_node, gf, vid, pid);
3952 		len = strlen(p) + 1;
3953 		p += len;
3954 		tlen -= len;
3955 	}
3956 
3957 	/* ( 8) scsiclass,DD.vV.pP */
3958 	if (*vid && *pid) {
3959 		*csp++ = p;
3960 		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s",
3961 		    dtype_node, vid, pid);
3962 		len = strlen(p) + 1;
3963 		p += len;
3964 		tlen -= len;
3965 	}
3966 
3967 	/* (8.5) scsa,DD.bB (not documented in scsi(4)) */
3968 	if (binding_set) {
3969 		*csp++ = p;
3970 		(void) snprintf(p, tlen, "scsa,%02x.b%s",
3971 		    dtype_node, binding_set);
3972 		len = strlen(p) + 1;
3973 		p += len;
3974 		tlen -= len;
3975 	}
3976 
3977 	/* ( 9) scsiclass,DDEEFFF */
3978 	if ((dtype_device != dtype_node) && *gf) {
3979 		*csp++ = p;
3980 		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s",
3981 		    dtype_node, dtype_device, gf);
3982 		len = strlen(p) + 1;
3983 		p += len;
3984 		tlen -= len;
3985 	}
3986 
3987 	/* (10) scsiclass,DDEE */
3988 	if (dtype_device != dtype_node) {
3989 		*csp++ = p;
3990 		(void) snprintf(p, tlen, "scsiclass,%02x%02x",
3991 		    dtype_node, dtype_device);
3992 		len = strlen(p) + 1;
3993 		p += len;
3994 		tlen -= len;
3995 	}
3996 
3997 	/* (11) scsiclass,DDFFF */
3998 	if (*gf) {
3999 		*csp++ = p;
4000 		(void) snprintf(p, tlen, "scsiclass,%02x%s",
4001 		    dtype_node, gf);
4002 		len = strlen(p) + 1;
4003 		p += len;
4004 		tlen -= len;
4005 	}
4006 
4007 	/* (12) scsiclass,DD */
4008 	*csp++ = p;
4009 	(void) snprintf(p, tlen, "scsiclass,%02x", dtype_node);
4010 	len = strlen(p) + 1;
4011 	p += len;
4012 	tlen -= len;
4013 
4014 	/* (12.5) scsa.fFFF */
4015 	if (*ff) {
4016 		*csp++ = p;
4017 		(void) snprintf(p, tlen, "scsa.f%s", ff);
4018 		len = strlen(p) + 1;
4019 		p += len;
4020 		tlen -= len;
4021 	}
4022 
4023 	/* (13) scsiclass */
4024 	*csp++ = p;
4025 	(void) snprintf(p, tlen, "scsiclass");
4026 	len = strlen(p) + 1;
4027 	p += len;
4028 	tlen -= len;
4029 	ASSERT(tlen >= 0);
4030 
4031 	*csp = NULL;			/* NULL terminate array of pointers */
4032 	ncompat = csp - compatp;
4033 
4034 	/*
4035 	 * When determining a nodename, a nodename_aliases specified
4036 	 * mapping has precedence over using a driver_aliases specified
4037 	 * driver binding as a nodename.
4038 	 *
4039 	 * See if any of the compatible forms have a nodename_aliases
4040 	 * specified nodename. These mappings are described by
4041 	 * nodename_aliases entries like:
4042 	 *
4043 	 *	disk		"scsiclass,00"
4044 	 *	enclosure	"scsiclass,03.vSYMBIOS.pD1000"
4045 	 *	ssd		"scsa,00.bfcp"
4046 	 *
4047 	 * All nodename_aliases mappings should idealy be to generic
4048 	 * names, however a higher precedence legacy mapping to a
4049 	 * driver name may exist. The highest precedence mapping
4050 	 * provides the nodename, so legacy driver nodename mappings
4051 	 * (if they exist) take precedence over generic nodename
4052 	 * mappings.
4053 	 */
4054 	for (nname = NULL, csp = compatp; (nname == NULL) && *csp; csp++) {
4055 		for (nap = na; nap->na_nodename; nap++) {
4056 			if (strcmp(*csp, nap->na_alias) == 0) {
4057 				nname = nap->na_nodename;
4058 				break;
4059 			}
4060 		}
4061 	}
4062 
4063 	/*
4064 	 * Determine the driver name based on compatible (which may
4065 	 * have the passed in compat0 as the first item). The driver_aliases
4066 	 * file has entries like
4067 	 *
4068 	 *	sd	"scsiclass,00"
4069 	 *
4070 	 * that map compatible forms to specific drivers. These entries are
4071 	 * established by add_drv/update_drv. We use the most specific
4072 	 * driver binding as the nodename. This matches the eventual
4073 	 * ddi_driver_compatible_major() binding that will be
4074 	 * established by bind_node()
4075 	 */
4076 	for (dname = NULL, csp = compatp; *csp; csp++) {
4077 		major = ddi_name_to_major(*csp);
4078 		if ((major == DDI_MAJOR_T_NONE) ||
4079 		    (devnamesp[major].dn_flags & DN_DRIVER_REMOVED))
4080 			continue;
4081 		if (dname = ddi_major_to_name(major))
4082 			break;
4083 	}
4084 
4085 	/*
4086 	 * If no nodename_aliases mapping exists then use the
4087 	 * driver_aliases specified driver binding as a nodename.
4088 	 */
4089 	if (nname == NULL)
4090 		nname = dname;
4091 
4092 	/* return results */
4093 	if (nname) {
4094 		*nodenamep = kmem_alloc(strlen(nname) + 1, KM_SLEEP);
4095 		(void) strcpy(*nodenamep, nname);
4096 	} else {
4097 		*nodenamep = NULL;
4098 
4099 		/*
4100 		 * If no nodename could be determined return a special
4101 		 * 'compatible' to be used for a diagnostic message. This
4102 		 * compatible contains all compatible forms concatenated
4103 		 * into a single string pointed to by the first element.
4104 		 */
4105 		for (csp = compatp; *(csp + 1); csp++)
4106 			*((*csp) + strlen(*csp)) = ' ';
4107 		*(compatp + 1) = NULL;
4108 		ncompat = 1;
4109 
4110 	}
4111 	if (drivernamep) {
4112 		if (dname) {
4113 			*drivernamep = kmem_alloc(strlen(dname) + 1, KM_SLEEP);
4114 			(void) strcpy(*drivernamep, dname);
4115 		} else
4116 			*drivernamep = NULL;
4117 	}
4118 	*compatiblep = compatp;
4119 	*ncompatiblep = ncompat;
4120 }
4121 
4122 /*
4123  * Free allocations associated with scsi_hba_ident_nodename_compatible_get.
4124  */
4125 static void
4126 scsi_hba_ident_nodename_compatible_free(char *nodename, char *drivername,
4127     char **compatible)
4128 {
4129 	if (nodename)
4130 		kmem_free(nodename, strlen(nodename) + 1);
4131 	if (drivername)
4132 		kmem_free(drivername, strlen(drivername) + 1);
4133 	if (compatible)
4134 		kmem_free(compatible, (NCOMPAT * sizeof (char *)) +
4135 		    (NCOMPAT * COMPAT_LONGEST));
4136 }
4137 
4138 void
4139 scsi_hba_nodename_compatible_get(struct scsi_inquiry *inq,
4140     char *binding_set, int dtype_node, char *compat0,
4141     char **nodenamep, char ***compatiblep, int *ncompatiblep)
4142 {
4143 	scsi_hba_ident_nodename_compatible_get(inq,
4144 	    NULL, 0, NULL, 0, binding_set, dtype_node, compat0, nodenamep,
4145 	    NULL, compatiblep, ncompatiblep);
4146 }
4147 
4148 void
4149 scsi_hba_nodename_compatible_free(char *nodename, char **compatible)
4150 {
4151 	scsi_hba_ident_nodename_compatible_free(nodename, NULL, compatible);
4152 }
4153 
4154 /* return the unit_address associated with a scsi_device */
4155 char *
4156 scsi_device_unit_address(struct scsi_device *sd)
4157 {
4158 	mdi_pathinfo_t	*pip;
4159 
4160 	ASSERT(sd && sd->sd_dev);
4161 	if ((sd == NULL) || (sd->sd_dev == NULL))
4162 		return (NULL);
4163 
4164 	pip = (mdi_pathinfo_t *)sd->sd_pathinfo;
4165 	if (pip)
4166 		return (mdi_pi_get_addr(pip));
4167 	else
4168 		return (ddi_get_name_addr(sd->sd_dev));
4169 }
4170 
4171 /* scsi_device property interfaces */
4172 #define	_TYPE_DEFINED(flags)						\
4173 	(((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_PATH) || \
4174 	((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_DEVICE))
4175 
4176 #define	_DEVICE_PIP(sd, flags)						\
4177 	((((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_PATH) && \
4178 	sd->sd_pathinfo) ? (mdi_pathinfo_t *)sd->sd_pathinfo : NULL)
4179 
4180 int
4181 scsi_device_prop_get_int(struct scsi_device *sd, uint_t flags,
4182     char *name, int defval)
4183 {
4184 	mdi_pathinfo_t	*pip;
4185 	int		v = defval;
4186 	int		data;
4187 	int		rv;
4188 
4189 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4190 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4191 	    !_TYPE_DEFINED(flags))
4192 		return (v);
4193 
4194 	pip = _DEVICE_PIP(sd, flags);
4195 	if (pip) {
4196 		rv = mdi_prop_lookup_int(pip, name, &data);
4197 		if (rv == DDI_PROP_SUCCESS)
4198 			v = data;
4199 	} else
4200 		v = ddi_prop_get_int(DDI_DEV_T_ANY, sd->sd_dev,
4201 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4202 	return (v);
4203 }
4204 
4205 
4206 int64_t
4207 scsi_device_prop_get_int64(struct scsi_device *sd, uint_t flags,
4208     char *name, int64_t defval)
4209 {
4210 	mdi_pathinfo_t	*pip;
4211 	int64_t		v = defval;
4212 	int64_t		data;
4213 	int		rv;
4214 
4215 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4216 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4217 	    !_TYPE_DEFINED(flags))
4218 		return (v);
4219 
4220 	pip = _DEVICE_PIP(sd, flags);
4221 	if (pip) {
4222 		rv = mdi_prop_lookup_int64(pip, name, &data);
4223 		if (rv == DDI_PROP_SUCCESS)
4224 			v = data;
4225 	} else
4226 		v = ddi_prop_get_int64(DDI_DEV_T_ANY, sd->sd_dev,
4227 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4228 	return (v);
4229 }
4230 
4231 int
4232 scsi_device_prop_lookup_byte_array(struct scsi_device *sd, uint_t flags,
4233     char *name, uchar_t **data, uint_t *nelements)
4234 {
4235 	mdi_pathinfo_t	*pip;
4236 	int		rv;
4237 
4238 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4239 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4240 	    !_TYPE_DEFINED(flags))
4241 		return (DDI_PROP_INVAL_ARG);
4242 
4243 	pip = _DEVICE_PIP(sd, flags);
4244 	if (pip)
4245 		rv = mdi_prop_lookup_byte_array(pip, name, data, nelements);
4246 	else
4247 		rv = ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, sd->sd_dev,
4248 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4249 		    name, data, nelements);
4250 	return (rv);
4251 }
4252 
4253 int
4254 scsi_device_prop_lookup_int_array(struct scsi_device *sd, uint_t flags,
4255     char *name, int **data, uint_t *nelements)
4256 {
4257 	mdi_pathinfo_t	*pip;
4258 	int		rv;
4259 
4260 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4261 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4262 	    !_TYPE_DEFINED(flags))
4263 		return (DDI_PROP_INVAL_ARG);
4264 
4265 	pip = _DEVICE_PIP(sd, flags);
4266 	if (pip)
4267 		rv = mdi_prop_lookup_int_array(pip, name, data, nelements);
4268 	else
4269 		rv = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, sd->sd_dev,
4270 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4271 		    name, data, nelements);
4272 	return (rv);
4273 }
4274 
4275 
4276 int
4277 scsi_device_prop_lookup_string(struct scsi_device *sd, uint_t flags,
4278     char *name, char **data)
4279 {
4280 	mdi_pathinfo_t	*pip;
4281 	int		rv;
4282 
4283 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4284 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4285 	    !_TYPE_DEFINED(flags))
4286 		return (DDI_PROP_INVAL_ARG);
4287 
4288 	pip = _DEVICE_PIP(sd, flags);
4289 	if (pip)
4290 		rv = mdi_prop_lookup_string(pip, name, data);
4291 	else
4292 		rv = ddi_prop_lookup_string(DDI_DEV_T_ANY, sd->sd_dev,
4293 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4294 		    name, data);
4295 	return (rv);
4296 }
4297 
4298 int
4299 scsi_device_prop_lookup_string_array(struct scsi_device *sd, uint_t flags,
4300     char *name, char ***data, uint_t *nelements)
4301 {
4302 	mdi_pathinfo_t	*pip;
4303 	int		rv;
4304 
4305 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4306 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4307 	    !_TYPE_DEFINED(flags))
4308 		return (DDI_PROP_INVAL_ARG);
4309 
4310 	pip = _DEVICE_PIP(sd, flags);
4311 	if (pip)
4312 		rv = mdi_prop_lookup_string_array(pip, name, data, nelements);
4313 	else
4314 		rv = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, sd->sd_dev,
4315 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4316 		    name, data, nelements);
4317 	return (rv);
4318 }
4319 
4320 int
4321 scsi_device_prop_update_byte_array(struct scsi_device *sd, uint_t flags,
4322     char *name, uchar_t *data, uint_t nelements)
4323 {
4324 	mdi_pathinfo_t	*pip;
4325 	int		rv;
4326 
4327 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4328 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4329 	    !_TYPE_DEFINED(flags))
4330 		return (DDI_PROP_INVAL_ARG);
4331 
4332 	pip = _DEVICE_PIP(sd, flags);
4333 	if (pip)
4334 		rv = mdi_prop_update_byte_array(pip, name, data, nelements);
4335 	else
4336 		rv = ndi_prop_update_byte_array(DDI_DEV_T_NONE, sd->sd_dev,
4337 		    name, data, nelements);
4338 	return (rv);
4339 }
4340 
4341 int
4342 scsi_device_prop_update_int(struct scsi_device *sd, uint_t flags,
4343     char *name, int data)
4344 {
4345 	mdi_pathinfo_t	*pip;
4346 	int		rv;
4347 
4348 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4349 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4350 	    !_TYPE_DEFINED(flags))
4351 		return (DDI_PROP_INVAL_ARG);
4352 
4353 	pip = _DEVICE_PIP(sd, flags);
4354 	if (pip)
4355 		rv = mdi_prop_update_int(pip, name, data);
4356 	else
4357 		rv = ndi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
4358 		    name, data);
4359 	return (rv);
4360 }
4361 
4362 int
4363 scsi_device_prop_update_int64(struct scsi_device *sd, uint_t flags,
4364     char *name, int64_t data)
4365 {
4366 	mdi_pathinfo_t	*pip;
4367 	int		rv;
4368 
4369 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4370 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4371 	    !_TYPE_DEFINED(flags))
4372 		return (DDI_PROP_INVAL_ARG);
4373 
4374 	pip = _DEVICE_PIP(sd, flags);
4375 	if (pip)
4376 		rv = mdi_prop_update_int64(pip, name, data);
4377 	else
4378 		rv = ndi_prop_update_int64(DDI_DEV_T_NONE, sd->sd_dev,
4379 		    name, data);
4380 	return (rv);
4381 }
4382 
4383 int
4384 scsi_device_prop_update_int_array(struct scsi_device *sd, uint_t flags,
4385     char *name, int *data, uint_t nelements)
4386 {
4387 	mdi_pathinfo_t	*pip;
4388 	int		rv;
4389 
4390 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4391 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4392 	    !_TYPE_DEFINED(flags))
4393 		return (DDI_PROP_INVAL_ARG);
4394 
4395 	pip = _DEVICE_PIP(sd, flags);
4396 	if (pip)
4397 		rv = mdi_prop_update_int_array(pip, name, data, nelements);
4398 	else
4399 		rv = ndi_prop_update_int_array(DDI_DEV_T_NONE, sd->sd_dev,
4400 		    name, data, nelements);
4401 	return (rv);
4402 }
4403 
4404 int
4405 scsi_device_prop_update_string(struct scsi_device *sd, uint_t flags,
4406     char *name, char *data)
4407 {
4408 	mdi_pathinfo_t	*pip;
4409 	int		rv;
4410 
4411 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4412 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4413 	    !_TYPE_DEFINED(flags))
4414 		return (DDI_PROP_INVAL_ARG);
4415 
4416 	pip = _DEVICE_PIP(sd, flags);
4417 	if (pip)
4418 		rv = mdi_prop_update_string(pip, name, data);
4419 	else
4420 		rv = ndi_prop_update_string(DDI_DEV_T_NONE, sd->sd_dev,
4421 		    name, data);
4422 	return (rv);
4423 }
4424 
4425 int
4426 scsi_device_prop_update_string_array(struct scsi_device *sd, uint_t flags,
4427     char *name, char **data, uint_t nelements)
4428 {
4429 	mdi_pathinfo_t	*pip;
4430 	int		rv;
4431 
4432 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4433 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4434 	    !_TYPE_DEFINED(flags))
4435 		return (DDI_PROP_INVAL_ARG);
4436 
4437 	pip = _DEVICE_PIP(sd, flags);
4438 	if (pip)
4439 		rv = mdi_prop_update_string_array(pip, name, data, nelements);
4440 	else
4441 		rv = ndi_prop_update_string_array(DDI_DEV_T_NONE, sd->sd_dev,
4442 		    name, data, nelements);
4443 	return (rv);
4444 }
4445 
4446 int
4447 scsi_device_prop_remove(struct scsi_device *sd, uint_t flags, char *name)
4448 {
4449 	mdi_pathinfo_t	*pip;
4450 	int		rv;
4451 
4452 	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4453 	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4454 	    !_TYPE_DEFINED(flags))
4455 		return (DDI_PROP_INVAL_ARG);
4456 
4457 	pip = _DEVICE_PIP(sd, flags);
4458 	if (pip)
4459 		rv = mdi_prop_remove(pip, name);
4460 	else
4461 		rv = ndi_prop_remove(DDI_DEV_T_NONE, sd->sd_dev, name);
4462 	return (rv);
4463 }
4464 
4465 void
4466 scsi_device_prop_free(struct scsi_device *sd, uint_t flags, void *data)
4467 {
4468 	mdi_pathinfo_t	*pip;
4469 
4470 	ASSERT(sd && data && sd->sd_dev && _TYPE_DEFINED(flags));
4471 	if ((sd == NULL) || (data == NULL) || (sd->sd_dev == NULL) ||
4472 	    !_TYPE_DEFINED(flags))
4473 		return;
4474 
4475 	pip = _DEVICE_PIP(sd, flags);
4476 	if (pip)
4477 		(void) mdi_prop_free(data);
4478 	else
4479 		ddi_prop_free(data);
4480 }
4481 
4482 /* SMP device property interfaces */
4483 int
4484 smp_device_prop_get_int(struct smp_device *smp_sd, char *name, int defval)
4485 {
4486 	int		v = defval;
4487 
4488 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4489 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4490 		return (v);
4491 
4492 	v = ddi_prop_get_int(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4493 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4494 	return (v);
4495 }
4496 
4497 
4498 int64_t
4499 smp_device_prop_get_int64(struct smp_device *smp_sd, char *name, int64_t defval)
4500 {
4501 	int64_t		v = defval;
4502 
4503 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4504 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4505 		return (v);
4506 
4507 	v = ddi_prop_get_int64(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4508 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4509 	return (v);
4510 }
4511 
4512 int
4513 smp_device_prop_lookup_byte_array(struct smp_device *smp_sd, char *name,
4514     uchar_t **data, uint_t *nelements)
4515 {
4516 	int		rv;
4517 
4518 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4519 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4520 		return (DDI_PROP_INVAL_ARG);
4521 
4522 	rv = ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4523 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4524 	    name, data, nelements);
4525 	return (rv);
4526 }
4527 
4528 int
4529 smp_device_prop_lookup_int_array(struct smp_device *smp_sd, char *name,
4530     int **data, uint_t *nelements)
4531 {
4532 	int		rv;
4533 
4534 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4535 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4536 		return (DDI_PROP_INVAL_ARG);
4537 
4538 	rv = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4539 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4540 	    name, data, nelements);
4541 	return (rv);
4542 }
4543 
4544 
4545 int
4546 smp_device_prop_lookup_string(struct smp_device *smp_sd, char *name,
4547     char **data)
4548 {
4549 	int		rv;
4550 
4551 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4552 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4553 		return (DDI_PROP_INVAL_ARG);
4554 
4555 	rv = ddi_prop_lookup_string(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4556 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4557 	    name, data);
4558 	return (rv);
4559 }
4560 
4561 int
4562 smp_device_prop_lookup_string_array(struct smp_device *smp_sd, char *name,
4563     char ***data, uint_t *nelements)
4564 {
4565 	int		rv;
4566 
4567 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4568 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4569 		return (DDI_PROP_INVAL_ARG);
4570 
4571 	rv = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4572 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4573 	    name, data, nelements);
4574 	return (rv);
4575 }
4576 
4577 int
4578 smp_device_prop_update_byte_array(struct smp_device *smp_sd, char *name,
4579     uchar_t *data, uint_t nelements)
4580 {
4581 	int		rv;
4582 
4583 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4584 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4585 		return (DDI_PROP_INVAL_ARG);
4586 
4587 	rv = ndi_prop_update_byte_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4588 	    name, data, nelements);
4589 	return (rv);
4590 }
4591 
4592 int
4593 smp_device_prop_update_int(struct smp_device *smp_sd, char *name, int data)
4594 {
4595 	int		rv;
4596 
4597 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4598 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4599 		return (DDI_PROP_INVAL_ARG);
4600 
4601 	rv = ndi_prop_update_int(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4602 	    name, data);
4603 	return (rv);
4604 }
4605 
4606 int
4607 smp_device_prop_update_int64(struct smp_device *smp_sd, char *name,
4608     int64_t data)
4609 {
4610 	int		rv;
4611 
4612 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4613 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4614 		return (DDI_PROP_INVAL_ARG);
4615 
4616 	rv = ndi_prop_update_int64(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4617 	    name, data);
4618 	return (rv);
4619 }
4620 
4621 int
4622 smp_device_prop_update_int_array(struct smp_device *smp_sd, char *name,
4623     int *data, uint_t nelements)
4624 {
4625 	int		rv;
4626 
4627 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4628 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4629 		return (DDI_PROP_INVAL_ARG);
4630 
4631 	rv = ndi_prop_update_int_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4632 	    name, data, nelements);
4633 	return (rv);
4634 }
4635 
4636 int
4637 smp_device_prop_update_string(struct smp_device *smp_sd, char *name, char *data)
4638 {
4639 	int		rv;
4640 
4641 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4642 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4643 		return (DDI_PROP_INVAL_ARG);
4644 
4645 	rv = ndi_prop_update_string(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4646 	    name, data);
4647 	return (rv);
4648 }
4649 
4650 int
4651 smp_device_prop_update_string_array(struct smp_device *smp_sd, char *name,
4652     char **data, uint_t nelements)
4653 {
4654 	int		rv;
4655 
4656 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4657 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4658 		return (DDI_PROP_INVAL_ARG);
4659 
4660 	rv = ndi_prop_update_string_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4661 	    name, data, nelements);
4662 	return (rv);
4663 }
4664 
4665 int
4666 smp_device_prop_remove(struct smp_device *smp_sd, char *name)
4667 {
4668 	int		rv;
4669 
4670 	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4671 	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4672 		return (DDI_PROP_INVAL_ARG);
4673 
4674 	rv = ndi_prop_remove(DDI_DEV_T_NONE, smp_sd->smp_sd_dev, name);
4675 	return (rv);
4676 }
4677 
4678 void
4679 smp_device_prop_free(struct smp_device *smp_sd, void *data)
4680 {
4681 	ASSERT(smp_sd && data && smp_sd->smp_sd_dev);
4682 	if ((smp_sd == NULL) || (data == NULL) || (smp_sd->smp_sd_dev == NULL))
4683 		return;
4684 
4685 	ddi_prop_free(data);
4686 }
4687 
4688 /*
4689  * scsi_hba_ua_set: given "unit-address" string, set properties.
4690  *
4691  * Function to set the properties on a devinfo or pathinfo node from
4692  * the "unit-address" part of a "name@unit-address" /devices path 'name'
4693  * string.
4694  *
4695  * This function works in conjunction with scsi_ua_get()/scsi_hba_ua_get()
4696  * (and possibly with an HBA driver's tran_tgt_init() implementation).
4697  */
4698 static int
4699 scsi_hba_ua_set(char *ua, dev_info_t *dchild, mdi_pathinfo_t *pchild)
4700 {
4701 	char		*p;
4702 	int		tgt;
4703 	char		*tgt_port_end;
4704 	char		*tgt_port;
4705 	int		tgt_port_len;
4706 	int		sfunc;
4707 	scsi_lun64_t	lun64;
4708 
4709 	/* Caller must choose to decorate devinfo *or* pathinfo */
4710 	ASSERT((dchild != NULL) ^ (pchild != NULL));
4711 	if (dchild && pchild)
4712 		return (0);
4713 
4714 	/*
4715 	 * generic implementation based on "tgt,lun[,sfunc]" address form.
4716 	 * parse hex "tgt" part of "tgt,lun[,sfunc]"
4717 	 */
4718 	p = ua;
4719 	tgt_port_end = NULL;
4720 	for (tgt = 0; *p && *p != ','; p++) {
4721 		if (*p >= '0' && *p <= '9')
4722 			tgt = (tgt << 4) + (*p - '0');
4723 		else if (*p >= 'a' && *p <= 'f')
4724 			tgt = (tgt << 4) + 10 + (*p - 'a');
4725 		else
4726 			tgt = -1;		/* non-numeric */
4727 
4728 		/*
4729 		 * if non-numeric or our of range set tgt to -1 and
4730 		 * skip forward
4731 		 */
4732 		if (tgt < 0) {
4733 			tgt = -1;
4734 			for (; *p && *p != ','; p++)
4735 				;
4736 			break;
4737 		}
4738 	}
4739 	tgt_port_end = p;
4740 
4741 	/* parse hex ",lun" part of "tgt,lun[,sfunc]" */
4742 	if (*p)
4743 		p++;
4744 	for (lun64 = 0; *p && *p != ','; p++) {
4745 		if (*p >= '0' && *p <= '9')
4746 			lun64 = (lun64 << 4) + (*p - '0');
4747 		else if (*p >= 'a' && *p <= 'f')
4748 			lun64 = (lun64 << 4) + 10 + (*p - 'a');
4749 		else
4750 			return (0);
4751 	}
4752 
4753 	/* parse hex ",sfunc" part of "tgt,lun[,sfunc]" */
4754 	if (*p) {
4755 		p++;
4756 		for (sfunc = 0; *p; p++) {
4757 			if (*p >= '0' && *p <= '9')
4758 				sfunc = (sfunc << 4) + (*p - '0');
4759 			else if (*p >= 'a' && *p <= 'f')
4760 				sfunc = (sfunc << 4) + 10 + (*p - 'a');
4761 			else
4762 				return (0);
4763 		}
4764 	} else
4765 		sfunc = -1;
4766 
4767 	if (dchild) {
4768 		/*
4769 		 * Decorate a devinfo node with unit address properties.
4770 		 * This adds the the addressing properties needed to
4771 		 * DDI_CTLOPS_UNINITCHILD the devinfo node (i.e. perform
4772 		 * the reverse operation - form unit address from properties).
4773 		 */
4774 		if ((tgt != -1) && (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4775 		    SCSI_ADDR_PROP_TARGET, tgt) != DDI_PROP_SUCCESS))
4776 			return (0);
4777 
4778 		if (tgt_port_end) {
4779 			tgt_port_len = tgt_port_end - ua + 1;
4780 			tgt_port = kmem_alloc(tgt_port_len, KM_SLEEP);
4781 			(void) strlcpy(tgt_port, ua, tgt_port_len);
4782 			if (ndi_prop_update_string(DDI_DEV_T_NONE, dchild,
4783 			    SCSI_ADDR_PROP_TARGET_PORT, tgt_port) !=
4784 			    DDI_PROP_SUCCESS) {
4785 				kmem_free(tgt_port, tgt_port_len);
4786 				return (0);
4787 			}
4788 			kmem_free(tgt_port, tgt_port_len);
4789 		}
4790 
4791 		/* Set the appropriate lun properties. */
4792 		if (lun64 < SCSI_32LUNS_PER_TARGET) {
4793 			if (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4794 			    SCSI_ADDR_PROP_LUN, (int)lun64) != DDI_PROP_SUCCESS)
4795 				return (0);
4796 		}
4797 		if (ndi_prop_update_int64(DDI_DEV_T_NONE, dchild,
4798 		    SCSI_ADDR_PROP_LUN64, lun64) != DDI_PROP_SUCCESS)
4799 			return (0);
4800 
4801 		/* Set the sfunc property */
4802 		if ((sfunc != -1) &&
4803 		    (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4804 		    SCSI_ADDR_PROP_SFUNC, (int)sfunc) != DDI_PROP_SUCCESS))
4805 			return (0);
4806 	} else if (pchild) {
4807 		/*
4808 		 * Decorate a pathinfo node with unit address properties.
4809 		 */
4810 		if ((tgt != -1) && (mdi_prop_update_int(pchild,
4811 		    SCSI_ADDR_PROP_TARGET, tgt) != DDI_PROP_SUCCESS))
4812 			return (0);
4813 
4814 		if (tgt_port_end) {
4815 			tgt_port_len = tgt_port_end - ua + 1;
4816 			tgt_port = kmem_alloc(tgt_port_len, KM_SLEEP);
4817 			(void) strlcpy(tgt_port, ua, tgt_port_len);
4818 			if (mdi_prop_update_string(pchild,
4819 			    SCSI_ADDR_PROP_TARGET_PORT, tgt_port) !=
4820 			    DDI_PROP_SUCCESS) {
4821 				kmem_free(tgt_port, tgt_port_len);
4822 				return (0);
4823 			}
4824 			kmem_free(tgt_port, tgt_port_len);
4825 		}
4826 
4827 		/* Set the appropriate lun properties */
4828 		if (lun64 < SCSI_32LUNS_PER_TARGET) {
4829 			if (mdi_prop_update_int(pchild, SCSI_ADDR_PROP_LUN,
4830 			    (int)lun64) != DDI_PROP_SUCCESS)
4831 				return (0);
4832 		}
4833 
4834 		if (mdi_prop_update_int64(pchild, SCSI_ADDR_PROP_LUN64,
4835 		    lun64) != DDI_PROP_SUCCESS)
4836 			return (0);
4837 
4838 		/* Set the sfunc property */
4839 		if ((sfunc != -1) &&
4840 		    (mdi_prop_update_int(pchild,
4841 		    SCSI_ADDR_PROP_SFUNC, (int)sfunc) != DDI_PROP_SUCCESS))
4842 			return (0);
4843 	}
4844 	return (1);
4845 }
4846 
4847 /*
4848  * Private ndi_devi_find/mdi_pi_find implementation - find the child
4849  * dev_info/path_info of self whose phci name matches "name@caddr".
4850  * We have our own implementation because we need to search with both
4851  * forms of sibling lists (dev_info and path_info) and we need to be able
4852  * to search with a NULL name in order to find siblings already associated
4853  * with a given unit-address (same @addr). NOTE: NULL name search will never
4854  * return probe node.
4855  *
4856  * If pchildp is NULL and we find a pathinfo child, we return the client
4857  * devinfo node in *dchildp.
4858  *
4859  * The init flag argument should be clear when called from places where
4860  * recursion could occur (like scsi_busctl_initchild) and when the caller
4861  * has already performed a search for name@addr with init set (performance).
4862  *
4863  * Future: Integrate ndi_devi_findchild_by_callback into scsi_hba_find_child.
4864  */
4865 static int
4866 scsi_hba_find_child(dev_info_t *self, char *name, char *addr, int init,
4867     dev_info_t **dchildp, mdi_pathinfo_t **pchildp, int *ppi)
4868 {
4869 	dev_info_t	*dchild;	/* devinfo child */
4870 	mdi_pathinfo_t	*pchild;	/* pathinfo child */
4871 	int		found = CHILD_TYPE_NONE;
4872 	char		*daddr;
4873 
4874 	ASSERT(self && DEVI_BUSY_OWNED(self));
4875 	ASSERT(addr && dchildp);
4876 	if ((self == NULL) || (addr == NULL) || (dchildp == NULL))
4877 		return (CHILD_TYPE_NONE);
4878 
4879 	*dchildp = NULL;
4880 	if (pchildp)
4881 		*pchildp = NULL;
4882 	if (ppi)
4883 		*ppi = 0;
4884 
4885 	/* Walk devinfo child list to find a match */
4886 	for (dchild = ddi_get_child(self); dchild;
4887 	    dchild = ddi_get_next_sibling(dchild)) {
4888 		if (i_ddi_node_state(dchild) < DS_INITIALIZED)
4889 			continue;
4890 
4891 		daddr = ddi_get_name_addr(dchild);
4892 		if (daddr && (strcmp(addr, daddr) == 0) &&
4893 		    ((name == NULL) ||
4894 		    (strcmp(name, DEVI(dchild)->devi_node_name) == 0))) {
4895 			/*
4896 			 * If we are asked to find "anything" at a given
4897 			 * unit-address (name == NULL), we don't realy want
4898 			 * to find the 'probe' node. The existance of
4899 			 * a probe node on a 'name == NULL' search should
4900 			 * fail.  This will trigger slow-path code where
4901 			 * we explicity look for, and synchronize against,
4902 			 * a node named "probe" at the unit-address.
4903 			 */
4904 			if ((name == NULL) &&
4905 			    scsi_hba_devi_is_barrier(dchild)) {
4906 				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4907 				    "%s@%s 'probe' devinfo found, skip",
4908 				    name ? name : "", addr));
4909 				continue;
4910 			}
4911 
4912 			/* We have found a match. */
4913 			found |= CHILD_TYPE_DEVINFO;
4914 			SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4915 			    "%s@%s devinfo found", name ? name : "", addr));
4916 			*dchildp = dchild;		/* devinfo found */
4917 			break;
4918 		}
4919 	}
4920 
4921 	/*
4922 	 * Walk pathinfo child list to find a match.
4923 	 *
4924 	 * NOTE: Unlike devinfo nodes, pathinfo nodes have a string searchable
4925 	 * unit-address from creation - so there is no need for an 'init'
4926 	 * search block of code for pathinfo nodes below.
4927 	 */
4928 	pchild = mdi_pi_find(self, NULL, addr);
4929 	if (pchild) {
4930 		/*
4931 		 * NOTE: If name specified and we match a pathinfo unit
4932 		 * address, we don't check the client node name.
4933 		 */
4934 		if (ppi)
4935 			*ppi = mdi_pi_get_path_instance(pchild);
4936 		found |= CHILD_TYPE_PATHINFO;
4937 
4938 		if (pchildp) {
4939 			SCSI_HBA_LOG((_LOG(4), self, NULL,
4940 			    "%s pathinfo found", mdi_pi_spathname(pchild)));
4941 			*pchildp = pchild;		/* pathinfo found */
4942 		} else if (*dchildp == NULL) {
4943 			/*
4944 			 * Did not find a devinfo node, found a pathinfo node,
4945 			 * but caller did not ask us to return a pathinfo node:
4946 			 * we return the 'client' devinfo node instead (but
4947 			 * with CHILD_TYPE_PATHINFO 'found' return value).
4948 			 */
4949 			dchild = mdi_pi_get_client(pchild);
4950 			SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4951 			    "%s pathinfo found, client switch",
4952 			    mdi_pi_spathname(pchild)));
4953 
4954 			/*
4955 			 * A pathinfo node always has a 'client' devinfo node,
4956 			 * but we need to ensure that the 'client' is
4957 			 * initialized and has a scsi_device structure too.
4958 			 */
4959 			ASSERT(dchild);
4960 			if (i_ddi_node_state(dchild) < DS_INITIALIZED) {
4961 				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4962 				    "%s found client, initchild",
4963 				    mdi_pi_spathname(pchild)));
4964 				(void) ddi_initchild(ddi_get_parent(dchild),
4965 				    dchild);
4966 			}
4967 			if (i_ddi_node_state(dchild) >= DS_INITIALIZED) {
4968 				/* client found and initialized */
4969 				*dchildp = dchild;
4970 			} else {
4971 				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4972 				    "%s found client, but failed initchild",
4973 				    mdi_pi_spathname(pchild)));
4974 			}
4975 		}
4976 	}
4977 
4978 	/* Try devinfo again with initchild of uninitialized nodes */
4979 	if ((found == CHILD_TYPE_NONE) && init) {
4980 		for (dchild = ddi_get_child(self); dchild;
4981 		    dchild = ddi_get_next_sibling(dchild)) {
4982 			/* skip if checked above */
4983 			if (i_ddi_node_state(dchild) >= DS_INITIALIZED)
4984 				continue;
4985 			/* attempt initchild to establish unit-address */
4986 			(void) ddi_initchild(self, dchild);
4987 			if (i_ddi_node_state(dchild) < DS_INITIALIZED)
4988 				continue;
4989 			daddr = ddi_get_name_addr(dchild);
4990 			if (daddr &&
4991 			    ((name == NULL) || (strcmp(name,
4992 			    DEVI(dchild)->devi_node_name) == 0)) &&
4993 			    (strcmp(addr, daddr) == 0)) {
4994 				found |= CHILD_TYPE_DEVINFO;
4995 				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4996 				    "%s@%s devinfo found post initchild",
4997 				    name ? name : "", addr));
4998 				*dchildp = dchild;	/* devinfo found */
4999 				break;	/* node found */
5000 			}
5001 		}
5002 	}
5003 
5004 	/*
5005 	 * We should never find devinfo and pathinfo at the same
5006 	 * unit-address.
5007 	 */
5008 	ASSERT(found != (CHILD_TYPE_DEVINFO | CHILD_TYPE_PATHINFO));
5009 	if (found == (CHILD_TYPE_DEVINFO | CHILD_TYPE_PATHINFO)) {
5010 		found = CHILD_TYPE_NONE;
5011 		*dchildp = NULL;
5012 		*pchildp = NULL;
5013 	}
5014 	return (found);
5015 }
5016 
5017 /*
5018  * Given information about a child device (contained on probe node) construct
5019  * and return a pointer to the dynamic SID devinfo node associated with the
5020  * device. In the creation of this SID node a compatible property for the
5021  * device is formed and used to establish a nodename (via
5022  * /etc/nodename_aliases) and to bind a driver (via /etc/driver_aliases).
5023  *
5024  * If this routine is called then we got a response from a device and
5025  * obtained the inquiry data from the device. Some inquiry results indicate
5026  * that the specific LUN we addressed does not exist, and we don't want to
5027  * bind a standard target driver to the node we create. Even though the
5028  * specific LUN is not usable, the framework may still want to bind a
5029  * target driver to the device for internal communication with the device -
5030  * an example would be issuing a report_lun to enumerate other LUNs under a
5031  * DPQ_NEVER LUN0. Another example would be wanting to known that the
5032  * DPQ_NEVER LUN0 device exists in BUS_CONFIG_ONE for non-existent LUN
5033  * caching optimizations. To support this we let the caller specify a
5034  * compatible property (or driver). If LUN0 inquiry data indicates that the
5035  * LUN does not exist then we establish compat0 as the highest precedence(0)
5036  * compatible form. If used, this compat0 driver will never be called on to
5037  * issue external commands to the device.
5038  *
5039  * If no driver binds to the device using driver_alias we establish the driver
5040  * passed in as the node name.
5041  */
5042 static int
5043 scsi_device_createchild(dev_info_t *self, char *addr, scsi_enum_t se,
5044     struct scsi_device *sdprobe, dev_info_t **dchildp, mdi_pathinfo_t **pchildp)
5045 {
5046 	scsi_lun64_t		lun64;
5047 	int			dtype;
5048 	int			dpq;
5049 	int			dpq_vu;
5050 	int			dtype_node;
5051 	int			lunexists;
5052 	char			*compat0;
5053 	char			*nname;
5054 	char			**compat = NULL;
5055 	int			ncompat;
5056 	dev_info_t		*dchild = NULL;
5057 	mdi_pathinfo_t		*pchild = NULL;
5058 	dev_info_t		*probe = sdprobe->sd_dev;
5059 	struct scsi_inquiry	*inq = sdprobe->sd_inq;
5060 	uchar_t			*inq80 = NULL;
5061 	uchar_t			*inq83 = NULL;
5062 	uint_t			inq80len, inq83len;
5063 	char			*binding_set = NULL;
5064 	char			*dname = NULL;
5065 	ddi_devid_t		devid;
5066 	int			have_devid = 0;
5067 	char			*devid_str;
5068 	char			*guid = NULL;
5069 
5070 	ASSERT(self && addr && *addr && DEVI_BUSY_OWNED(self));
5071 	ASSERT(dchildp && pchildp);
5072 
5073 	/*
5074 	 * Determine the lun and whether the lun exists. We may need to create
5075 	 * a node for LUN0 (with compat0 driver binding) even if the lun does
5076 	 * not exist - so we can run report_lun to find additional LUNs.
5077 	 */
5078 	lun64 = scsi_addr_to_lun64(addr);
5079 	dtype = inq->inq_dtype & DTYPE_MASK;		/* device */
5080 	dpq = inq->inq_dtype & DPQ_MASK;
5081 	dpq_vu = inq->inq_dtype & DPQ_VUNIQ ? 1 : 0;
5082 
5083 	dtype_node = scsi_addr_to_sfunc(addr);		/* secondary function */
5084 	if (dtype_node == -1)
5085 		dtype_node = dtype;			/* node for device */
5086 
5087 	lunexists = (dtype != dtype_node) ||		/* override */
5088 	    ((dpq_vu == 0) && (dpq == DPQ_POSSIBLE)) ||	/* ANSII */
5089 	    (dpq_vu && (lun64 == 0));			/* VU LUN0 */
5090 	if (dtype == DTYPE_UNKNOWN)
5091 		lunexists = 0;
5092 
5093 	SCSI_HBA_LOG((_LOG(4), self, NULL,
5094 	    "@%s dtype %x %x dpq_vu %d dpq %x: %d",
5095 	    addr, dtype, dtype_node, dpq_vu, dpq, lunexists));
5096 
5097 	/* A non-existent LUN0 uses compatible_nodev. */
5098 	if (lunexists) {
5099 		compat0 = NULL;				/* compat0 not needed */
5100 	} else if (lun64 == 0) {
5101 		compat0 = compatible_nodev;
5102 		SCSI_HBA_LOG((_LOG(2), self, NULL,
5103 		    "@%s lun 0 with compat0 %s", addr, compat0));
5104 	} else
5105 		goto out;				/* no node created */
5106 
5107 	/* Obtain identity information from probe node. */
5108 	if (ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, probe,
5109 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "inquiry-page-80",
5110 	    &inq80, &inq80len) != DDI_PROP_SUCCESS)
5111 		inq80 = NULL;
5112 	if (ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, probe,
5113 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "inquiry-page-83",
5114 	    &inq83, &inq83len) != DDI_PROP_SUCCESS)
5115 		inq83 = NULL;
5116 
5117 	/* Get "scsi-binding-set" property (if there is one). */
5118 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
5119 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
5120 	    "scsi-binding-set", &binding_set) == DDI_PROP_SUCCESS)
5121 		SCSI_HBA_LOG((_LOG(2), NULL, probe,
5122 		    "binding_set '%s'", binding_set));
5123 
5124 	/* determine the node name and compatible information */
5125 	scsi_hba_ident_nodename_compatible_get(inq,
5126 	    inq80, inq80len, inq83, inq83len, binding_set, dtype_node,
5127 	    compat0, &nname, &dname, &compat, &ncompat);
5128 
5129 	if (nname == NULL) {
5130 		/*
5131 		 * We will not be able to create a node because we could not
5132 		 * determine a node name. Print out a NODRIVER level warning
5133 		 * message with the compatible forms for the device. Note that
5134 		 * there may be a driver.conf node that attaches to the device,
5135 		 * which is why we only produce this warning message for debug
5136 		 * kernels.
5137 		 */
5138 		SCSI_HBA_LOG((_LOG(1), NULL, self,
5139 		    "no node_name for device @%s:\n         compatible: %s",
5140 		    addr, *compat));
5141 		goto out;
5142 	}
5143 
5144 	/*
5145 	 * FUTURE: some day we may want an accurate "compatible" on the probe
5146 	 * node so that vhci_is_dev_supported() in scsi_vhci could, at
5147 	 * least in part, determine/configure based on "compatible".
5148 	 *
5149 	 *	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, probe,
5150 	 *	    "compatible", compat, ncompat) != DDI_PROP_SUCCESS) {
5151 	 *		SCSI_HBA_LOG((_LOG(3), self, NULL,
5152 	 *		    "%s@%s failed probe compatible decoration",
5153 	 *		    nname, addr));
5154 	 *		goto out;
5155 	 *	}
5156 	 */
5157 
5158 	/* Encode devid from identity information. */
5159 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST, dname,
5160 	    (uchar_t *)inq, sizeof (*inq), inq80, inq80len, inq83, inq83len,
5161 	    &devid) == DDI_SUCCESS) {
5162 		have_devid = 1;
5163 
5164 		/* Attempt to form guid from devid. */
5165 		guid = ddi_devid_to_guid(devid);
5166 
5167 		/* Produce string devid for debug. */
5168 		devid_str = ddi_devid_str_encode(devid, NULL);
5169 		SCSI_HBA_LOG((_LOG(3), self, probe, "devid '%s' guid '%s'",
5170 		    devid_str ? devid_str : "NULL", guid ? guid : "NULL"));
5171 		ddi_devid_str_free(devid_str);
5172 	}
5173 
5174 
5175 	/*
5176 	 * Determine if the device should be enumerated as under the vHCI
5177 	 * (client node) or under the pHCI. By convention scsi_vhci expects
5178 	 * the "cinfo" argument identity information to be represented as a
5179 	 * devinfo node with the needed information (i.e. the pHCI probe node).
5180 	 */
5181 	if ((guid == NULL) ||
5182 	    (mdi_is_dev_supported(MDI_HCI_CLASS_SCSI, self, sdprobe) !=
5183 	    MDI_SUCCESS)) {
5184 		SCSI_HBA_LOG((_LOG(3), self, probe, "==> devinfo"));
5185 
5186 		/*
5187 		 * Enumerate under pHCI:
5188 		 *
5189 		 * Create dynamic SID dchild node. No attempt is made to
5190 		 * transfer information (except the addressing and identity
5191 		 * information) from the probe node to the dynamic node since
5192 		 * there may be HBA specific side effects that the framework
5193 		 * does not known how to transfer.
5194 		 */
5195 		ndi_devi_alloc_sleep(self, nname,
5196 		    (se == SE_HP) ? DEVI_SID_HP_NODEID : DEVI_SID_NODEID,
5197 		    &dchild);
5198 		ASSERT(dchild);
5199 		ndi_flavor_set(dchild, SCSA_FLAVOR_SCSI_DEVICE);
5200 
5201 		/*
5202 		 * Decorate new node with addressing properties (via
5203 		 * scsi_hba_ua_set()), compatible, identity information, and
5204 		 * class.
5205 		 */
5206 		if ((scsi_hba_ua_set(addr, dchild, NULL) == 0) ||
5207 		    (ndi_prop_update_string_array(DDI_DEV_T_NONE, dchild,
5208 		    "compatible", compat, ncompat) != DDI_PROP_SUCCESS) ||
5209 		    (inq80 && (ndi_prop_update_byte_array(DDI_DEV_T_NONE,
5210 		    dchild, "inquiry-page-80", inq80, inq80len) !=
5211 		    DDI_PROP_SUCCESS)) ||
5212 		    (inq83 && (ndi_prop_update_byte_array(DDI_DEV_T_NONE,
5213 		    dchild, "inquiry-page-83", inq83, inq83len) !=
5214 		    DDI_PROP_SUCCESS)) ||
5215 		    (ndi_prop_update_string(DDI_DEV_T_NONE, dchild,
5216 		    "class", "scsi") != DDI_PROP_SUCCESS)) {
5217 			SCSI_HBA_LOG((_LOG(2), self, NULL,
5218 			    "@%s failed devinfo decoration", addr));
5219 			(void) scsi_hba_remove_node(dchild);
5220 			dchild = NULL;
5221 			goto out;
5222 		}
5223 
5224 		/* Bind the driver */
5225 		if (ndi_devi_bind_driver(dchild, 0) != NDI_SUCCESS) {
5226 			/* need to bind in order to register a devid */
5227 			SCSI_HBA_LOG((_LOGCFG, NULL, dchild,
5228 			    "devinfo @%s created, no driver-> "
5229 			    "no devid_register", addr));
5230 			goto out;
5231 		}
5232 
5233 		/* Register devid */
5234 		if (have_devid) {
5235 			if (ddi_devid_register(dchild, devid) == DDI_FAILURE)
5236 				SCSI_HBA_LOG((_LOG(1), NULL, dchild,
5237 				    "devinfo @%s created, "
5238 				    "devid register failed", addr));
5239 			else
5240 				SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5241 				    "devinfo @%s created with devid", addr));
5242 		} else
5243 			SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5244 			    "devinfo @%s created, no devid", addr));
5245 	} else {
5246 		/*
5247 		 * Enumerate under vHCI:
5248 		 *
5249 		 * Create a pathinfo pchild node.
5250 		 */
5251 		SCSI_HBA_LOG((_LOG(3), self, probe, "==>pathinfo"));
5252 
5253 		if (mdi_pi_alloc_compatible(self, nname, guid, addr, compat,
5254 		    ncompat, 0, &pchild) != MDI_SUCCESS) {
5255 			SCSI_HBA_LOG((_LOG(2), self, probe,
5256 			    "pathinfo alloc failed"));
5257 			goto out;
5258 		}
5259 		ASSERT(pchild);
5260 
5261 		/*
5262 		 * Decorate new node with addressing properties via
5263 		 * scsi_hba_ua_set().
5264 		 */
5265 		if (scsi_hba_ua_set(addr, NULL, pchild) == 0) {
5266 			SCSI_HBA_LOG((_LOG(1), self, NULL,
5267 			    "%s pathinfo decoration failed",
5268 			    mdi_pi_spathname(pchild)));
5269 
5270 			/* For hotplug, path exists even on failure. */
5271 			if (se != SE_HP)
5272 				(void) mdi_pi_free(pchild, 0);
5273 			goto out;
5274 		}
5275 	}
5276 
5277 	/* free the node name and compatible information */
5278 out:	if (have_devid)
5279 		ddi_devid_free(devid);
5280 	if (guid)
5281 		ddi_devid_free_guid(guid);
5282 	if (compat)
5283 		scsi_hba_ident_nodename_compatible_free(nname, dname, compat);
5284 	if (inq80)
5285 		ddi_prop_free(inq80);
5286 	if (inq83)
5287 		ddi_prop_free(inq83);
5288 	if (binding_set)
5289 		ddi_prop_free(binding_set);
5290 
5291 	/* return child_type results */
5292 	ASSERT(!(dchild && pchild));
5293 	if (dchild) {
5294 		*dchildp = dchild;
5295 		*pchildp = NULL;
5296 		return (CHILD_TYPE_DEVINFO);
5297 	}
5298 	if (pchild) {
5299 		*dchildp = NULL;
5300 		*pchildp = pchild;
5301 		return (CHILD_TYPE_PATHINFO);
5302 	}
5303 	return (CHILD_TYPE_NONE);
5304 }
5305 
5306 /*
5307  * Call scsi_device_createchild and then initchild the new node.
5308  */
5309 static dev_info_t *
5310 scsi_device_configchild(dev_info_t *self, char *addr, scsi_enum_t se,
5311     struct scsi_device *sdprobe, int *circp, int *ppi)
5312 {
5313 	int		child_type;
5314 	dev_info_t	*dchild;
5315 	mdi_pathinfo_t	*pchild;
5316 	dev_info_t	*child;
5317 	int		rval;
5318 
5319 	ASSERT(self && addr && *addr && DEVI_BUSY_OWNED(self));
5320 	if (ppi)
5321 		*ppi = 0;
5322 
5323 	child_type = scsi_device_createchild(self, addr, se, sdprobe,
5324 	    &dchild, &pchild);
5325 
5326 	/*
5327 	 * Prevent multiple initialized (tran_tgt_init) nodes associated with
5328 	 * the same @addr at the same time by calling tran_tgt_free() on the
5329 	 * probe node prior to promotion of the 'real' node.  After the call
5330 	 * to scsi_hba_barrier_tran_tgt_free(), the HBA no longer has any
5331 	 * probe node context.
5332 	 */
5333 	scsi_hba_barrier_tran_tgt_free(sdprobe->sd_dev);
5334 
5335 	switch (child_type) {
5336 	case CHILD_TYPE_NONE:
5337 		child = NULL;
5338 		break;
5339 
5340 	case CHILD_TYPE_PATHINFO:
5341 		/*
5342 		 * Online pathinfo: Hold the path and exit the pHCI while
5343 		 * calling mdi_pi_online() to avoid deadlock with power
5344 		 * management of pHCI.
5345 		 */
5346 		ASSERT(MDI_PHCI(self));
5347 		mdi_hold_path(pchild);
5348 		scsi_hba_devi_exit_phci(self, *circp);
5349 
5350 		rval = mdi_pi_online(pchild, 0);
5351 
5352 		scsi_hba_devi_enter_phci(self, circp);
5353 		mdi_rele_path(pchild);
5354 
5355 		if (rval != MDI_SUCCESS) {
5356 			SCSI_HBA_LOG((_LOG(2), self, NULL,
5357 			    "%s pathinfo online failed",
5358 			    mdi_pi_spathname(pchild)));
5359 
5360 			/* For hotplug, path exists even when online fails */
5361 			if (se != SE_HP)
5362 				(void) mdi_pi_free(pchild, 0);
5363 			return (NULL);
5364 		}
5365 
5366 		/*
5367 		 * Return the path_instance of the pathinfo node.
5368 		 *
5369 		 * NOTE: We assume that sd_inq is not path-specific.
5370 		 */
5371 		if (ppi)
5372 			*ppi = mdi_pi_get_path_instance(pchild);
5373 
5374 
5375 		/*
5376 		 * Fallthrough into CHILD_TYPE_DEVINFO code to promote
5377 		 * the 'client' devinfo node as a dchild.
5378 		 */
5379 		dchild = mdi_pi_get_client(pchild);
5380 		SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5381 		    "pathinfo online successful"));
5382 		/* FALLTHROUGH */
5383 
5384 	case CHILD_TYPE_DEVINFO:
5385 		/*
5386 		 * For now, we ndi_devi_online() the child because some other
5387 		 * parts of the IO framework, like degenerate devid code,
5388 		 * depend on bus_config driving nodes to DS_ATTACHED. At some
5389 		 * point in the future, to keep things light-weight, we would
5390 		 * like to change the ndi_devi_online call below to be
5391 		 *
5392 		 *	if (ddi_initchild(self, dchild) != DDI_SUCCESS)
5393 		 *
5394 		 * This would promote the node so that framework code could
5395 		 * find the child with an @addr search, but does not incur
5396 		 * attach(9E) overhead for BUS_CONFIG_ALL cases where the
5397 		 * framework is not interested in attach of the node.
5398 		 *
5399 		 * NOTE: If the addr specified has incorrect syntax (busconfig
5400 		 * one of bogus /devices path) then call below can fail.
5401 		 */
5402 		if (ndi_devi_online(dchild, 0) != NDI_SUCCESS) {
5403 			SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5404 			    "devinfo online failed"));
5405 
5406 			/* failed online does not remove the node */
5407 			(void) scsi_hba_remove_node(dchild);
5408 			return (NULL);
5409 		}
5410 		SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5411 		    "devinfo initchild successful"));
5412 		child = dchild;
5413 		break;
5414 	}
5415 	return (child);
5416 }
5417 
5418 void
5419 scsi_hba_pkt_comp(struct scsi_pkt *pkt)
5420 {
5421 	scsi_hba_tran_t	*tran;
5422 	uint8_t		*sensep;
5423 
5424 	ASSERT(pkt);
5425 
5426 	/*
5427 	 * Catch second call on the same packet before doing anything else.
5428 	 */
5429 	if (pkt->pkt_flags & FLAG_PKT_COMP_CALLED) {
5430 		cmn_err(
5431 #ifdef DEBUG
5432 		    CE_PANIC,
5433 #else
5434 		    CE_WARN,
5435 #endif
5436 		    "%s duplicate scsi_hba_pkt_comp(9F) on same scsi_pkt(9S)",
5437 		    mod_containing_pc(caller()));
5438 	}
5439 
5440 	pkt->pkt_flags |= FLAG_PKT_COMP_CALLED;
5441 
5442 	if (pkt->pkt_comp == NULL)
5443 		return;
5444 
5445 	/*
5446 	 * For HBA drivers that implement tran_setup_pkt(9E), if we are
5447 	 * completing a 'consistent' mode DMA operation then we must
5448 	 * perform dma_sync prior to calling pkt_comp to ensure that
5449 	 * the target driver sees the correct data in memory.
5450 	 */
5451 	ASSERT((pkt->pkt_flags & FLAG_NOINTR) == 0);
5452 	if (((pkt->pkt_dma_flags & DDI_DMA_CONSISTENT) &&
5453 	    (pkt->pkt_dma_flags & DDI_DMA_READ)) &&
5454 	    ((P_TO_TRAN(pkt)->tran_setup_pkt) != NULL)) {
5455 		scsi_sync_pkt(pkt);
5456 	}
5457 
5458 	/*
5459 	 * If the HBA driver is using SCSAv3 scsi_hba_tgtmap_create enumeration
5460 	 * then we detect the special ASC/ASCQ completion codes that indicate
5461 	 * that the lun configuration of a target has changed. Since we need to
5462 	 * be determine scsi_device given scsi_address enbedded in
5463 	 * scsi_pkt (via scsi_address_device(9F)), we also require use of
5464 	 * SCSI_HBA_ADDR_COMPLEX.
5465 	 */
5466 	tran = pkt->pkt_address.a_hba_tran;
5467 	ASSERT(tran);
5468 	if ((tran->tran_tgtmap == NULL) ||
5469 	    !(tran->tran_hba_flags & SCSI_HBA_ADDR_COMPLEX))
5470 		goto comp;		/* not using tgtmap */
5471 
5472 	/*
5473 	 * Check for lun-change notification and queue the scsi_pkt for
5474 	 * lunchg1 processing. The 'pkt_comp' call to the target driver
5475 	 * is part of lunchg1 processing.
5476 	 */
5477 	if ((pkt->pkt_reason == CMD_CMPLT) &&
5478 	    (((*pkt->pkt_scbp) & STATUS_MASK) == STATUS_CHECK) &&
5479 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
5480 		sensep = (uint8_t *)&(((struct scsi_arq_status *)(uintptr_t)
5481 		    (pkt->pkt_scbp))->sts_sensedata);
5482 		if (((scsi_sense_key(sensep) == KEY_UNIT_ATTENTION) &&
5483 		    (scsi_sense_asc(sensep) == 0x3f) &&
5484 		    (scsi_sense_ascq(sensep) == 0x0e)) ||
5485 
5486 		    ((scsi_sense_key(sensep) == KEY_UNIT_ATTENTION) &&
5487 		    (scsi_sense_asc(sensep) == 0x25) &&
5488 		    (scsi_sense_ascq(sensep) == 0x00))) {
5489 			/*
5490 			 * The host adaptor is done with the packet, we use
5491 			 * pkt_stmp stage-temporary to link the packet for
5492 			 * lunchg1 processing.
5493 			 *
5494 			 * NOTE: pkt_ha_private is not available since its use
5495 			 * extends to tran_teardown_pkt.
5496 			 */
5497 			mutex_enter(&scsi_lunchg1_mutex);
5498 			pkt->pkt_stmp = scsi_lunchg1_list;
5499 			scsi_lunchg1_list = pkt;
5500 			if (pkt->pkt_stmp == NULL)
5501 				(void) cv_signal(&scsi_lunchg1_cv);
5502 			mutex_exit(&scsi_lunchg1_mutex);
5503 			return;
5504 		}
5505 	}
5506 
5507 comp:	(*pkt->pkt_comp)(pkt);
5508 }
5509 
5510 /*
5511  * return 1 if the specified node is a barrier/probe node
5512  */
5513 static int
5514 scsi_hba_devi_is_barrier(dev_info_t *probe)
5515 {
5516 	if (probe && (strcmp(ddi_node_name(probe), "probe") == 0))
5517 		return (1);
5518 	return (0);
5519 }
5520 
5521 /*
5522  * A host adapter driver is easier to write if we prevent multiple initialized
5523  * (tran_tgt_init) scsi_device structures to the same unit-address at the same
5524  * time.  We prevent this from occurring all the time during the barrier/probe
5525  * node to real child hand-off by calling scsi_hba_barrier_tran_tgt_free
5526  * on the probe node prior to ddi_inichild of the 'real' node.  As part of
5527  * this early tran_tgt_free implementation, we must also call this function
5528  * as we put a probe node on the scsi_hba_barrier_list.
5529  */
5530 static void
5531 scsi_hba_barrier_tran_tgt_free(dev_info_t *probe)
5532 {
5533 	struct scsi_device	*sdprobe;
5534 	dev_info_t		*self;
5535 	scsi_hba_tran_t		*tran;
5536 
5537 	ASSERT(probe && scsi_hba_devi_is_barrier(probe));
5538 
5539 	/* Return if we never called tran_tgt_init(9E). */
5540 	if (i_ddi_node_state(probe) < DS_INITIALIZED)
5541 		return;
5542 
5543 	sdprobe = ddi_get_driver_private(probe);
5544 	self = ddi_get_parent(probe);
5545 	ASSERT(sdprobe && self);
5546 	tran = ddi_get_driver_private(self);
5547 	ASSERT(tran);
5548 
5549 	if (tran->tran_tgt_free) {
5550 		/*
5551 		 * To correctly support TRAN_CLONE, we need to use the same
5552 		 * cloned scsi_hba_tran(9S) structure for both tran_tgt_init(9E)
5553 		 * and tran_tgt_free(9E).
5554 		 */
5555 		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE)
5556 			tran = sdprobe->sd_address.a_hba_tran;
5557 		SCSI_HBA_LOG((_LOG(4), NULL, probe, "tran_tgt_free EARLY"));
5558 
5559 		(*tran->tran_tgt_free) (self, probe, tran, sdprobe);
5560 	}
5561 }
5562 
5563 /*
5564  * Add an entry to the list of barrier nodes to be asynchronously deleted by
5565  * the scsi_hba_barrier_daemon after the specified timeout. Nodes on
5566  * the barrier list are used to implement the bus_config probe cache
5567  * of non-existent devices. The nodes are at DS_INITIALIZED, so their
5568  * @addr is established for searching. Since devi_ref of a DS_INITIALIZED
5569  * node will *not* prevent demotion, demotion is prevented by setting
5570  * sd_uninit_prevent. Devinfo snapshots attempt to attach probe cache
5571  * nodes, and on failure attempt to demote the node (without the participation
5572  * of bus_unconfig) to DS_BOUND - this demotion is prevented via
5573  * sd_uninit_prevent causing any attempted DDI_CTLOPS_UNINITCHILD to fail.
5574  * Probe nodes are bound to nulldriver. The list is sorted by
5575  * expiration time.
5576  *
5577  * NOTE: If we drove a probe node to DS_ATTACHED, we could use ndi_hold_devi()
5578  * to prevent demotion (instead of sd_uninit_prevent).
5579  */
5580 static void
5581 scsi_hba_barrier_add(dev_info_t *probe, int seconds)
5582 {
5583 	struct scsi_hba_barrier	*nb;
5584 	struct scsi_hba_barrier	*b;
5585 	struct scsi_hba_barrier	**bp;
5586 	clock_t			endtime;
5587 
5588 	ASSERT(scsi_hba_devi_is_barrier(probe));
5589 
5590 	/* HBA is no longer responsible for nodes on the barrier list. */
5591 	scsi_hba_barrier_tran_tgt_free(probe);
5592 
5593 	nb = kmem_alloc(sizeof (struct scsi_hba_barrier), KM_SLEEP);
5594 	mutex_enter(&scsi_hba_barrier_mutex);
5595 	endtime = ddi_get_lbolt() + drv_usectohz(seconds * MICROSEC);
5596 	for (bp = &scsi_hba_barrier_list; (b = *bp) != NULL;
5597 	    bp = &b->barrier_next)
5598 		if (b->barrier_endtime > endtime)
5599 			break;
5600 	nb->barrier_next = *bp;
5601 	nb->barrier_endtime = endtime;
5602 	nb->barrier_probe = probe;
5603 	*bp = nb;
5604 	if (bp == &scsi_hba_barrier_list)
5605 		(void) cv_signal(&scsi_hba_barrier_cv);
5606 	mutex_exit(&scsi_hba_barrier_mutex);
5607 }
5608 
5609 /*
5610  * Attempt to remove devinfo node node, return 1 if removed. We don't
5611  * don't try to remove barrier nodes that have sd_uninit_prevent set
5612  * (even though they should fail device_uninitchild).
5613  */
5614 static int
5615 scsi_hba_remove_node(dev_info_t *child)
5616 {
5617 	dev_info_t		*self = ddi_get_parent(child);
5618 	struct scsi_device	*sd;
5619 	int			circ;
5620 	int			remove = 1;
5621 	int			ret = 0;
5622 	char			na[SCSI_MAXNAMELEN];
5623 
5624 	scsi_hba_devi_enter(self, &circ);
5625 
5626 	/* Honor sd_uninit_prevent on barrier nodes */
5627 	if (scsi_hba_devi_is_barrier(child)) {
5628 		sd = ddi_get_driver_private(child);
5629 		if (sd && sd->sd_uninit_prevent)
5630 			remove = 0;
5631 	}
5632 
5633 	if (remove) {
5634 		(void) ddi_deviname(child, na);
5635 		if (ddi_remove_child(child, 0) != DDI_SUCCESS) {
5636 			SCSI_HBA_LOG((_LOG(2), NULL, child,
5637 			    "remove_node failed"));
5638 		} else {
5639 			child = NULL;		/* child is gone */
5640 			SCSI_HBA_LOG((_LOG(4), self, NULL,
5641 			    "remove_node removed %s", *na ? &na[1] : na));
5642 			ret = 1;
5643 		}
5644 	} else {
5645 		SCSI_HBA_LOG((_LOG(4), NULL, child, "remove_node prevented"));
5646 	}
5647 	scsi_hba_devi_exit(self, circ);
5648 	return (ret);
5649 }
5650 
5651 /*
5652  * The asynchronous barrier deletion daemon. Waits for a barrier timeout
5653  * to expire, then deletes the barrier (removes it as a child).
5654  */
5655 /*ARGSUSED*/
5656 static void
5657 scsi_hba_barrier_daemon(void *arg)
5658 {
5659 	struct scsi_hba_barrier	*b;
5660 	dev_info_t		*probe;
5661 	callb_cpr_t		cprinfo;
5662 	int			circ;
5663 	dev_info_t		*self;
5664 
5665 	CALLB_CPR_INIT(&cprinfo, &scsi_hba_barrier_mutex,
5666 	    callb_generic_cpr, "scsi_hba_barrier_daemon");
5667 again:	mutex_enter(&scsi_hba_barrier_mutex);
5668 	for (;;) {
5669 		b = scsi_hba_barrier_list;
5670 		if (b == NULL) {
5671 			/* all barriers expired, wait for barrier_add */
5672 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5673 			(void) cv_wait(&scsi_hba_barrier_cv,
5674 			    &scsi_hba_barrier_mutex);
5675 			CALLB_CPR_SAFE_END(&cprinfo, &scsi_hba_barrier_mutex);
5676 		} else {
5677 			if (ddi_get_lbolt() >= b->barrier_endtime) {
5678 				/*
5679 				 * Drop and retry if ordering issue. Do this
5680 				 * before calling scsi_hba_remove_node() and
5681 				 * deadlocking.
5682 				 */
5683 				probe = b->barrier_probe;
5684 				self = ddi_get_parent(probe);
5685 				if (scsi_hba_devi_tryenter(self, &circ) == 0) {
5686 delay:					mutex_exit(&scsi_hba_barrier_mutex);
5687 					delay_random(5);
5688 					goto again;
5689 				}
5690 
5691 				/* process expired barrier */
5692 				if (!scsi_hba_remove_node(probe)) {
5693 					/* remove failed, delay and retry */
5694 					SCSI_HBA_LOG((_LOG(4), NULL, probe,
5695 					    "delay expire"));
5696 					scsi_hba_devi_exit(self, circ);
5697 					goto delay;
5698 				}
5699 				scsi_hba_barrier_list = b->barrier_next;
5700 				kmem_free(b, sizeof (struct scsi_hba_barrier));
5701 				scsi_hba_devi_exit(self, circ);
5702 			} else {
5703 				/* establish timeout for next barrier expire */
5704 				(void) cv_timedwait(&scsi_hba_barrier_cv,
5705 				    &scsi_hba_barrier_mutex,
5706 				    b->barrier_endtime);
5707 			}
5708 		}
5709 	}
5710 }
5711 
5712 /*
5713  * Remove all barriers associated with the specified HBA. This is called
5714  * from from the bus_unconfig implementation to remove probe nodes associated
5715  * with the specified HBA (self) so that probe nodes that have not expired
5716  * will not prevent DR of the HBA.
5717  */
5718 static void
5719 scsi_hba_barrier_purge(dev_info_t *self)
5720 {
5721 	struct scsi_hba_barrier	**bp;
5722 	struct scsi_hba_barrier	*b;
5723 
5724 	mutex_enter(&scsi_hba_barrier_mutex);
5725 	for (bp = &scsi_hba_barrier_list; (b = *bp) != NULL; ) {
5726 		if (ddi_get_parent(b->barrier_probe) == self) {
5727 			if (scsi_hba_remove_node(b->barrier_probe)) {
5728 				*bp = b->barrier_next;
5729 				kmem_free(b, sizeof (struct scsi_hba_barrier));
5730 			} else {
5731 				SCSI_HBA_LOG((_LOG(4), NULL, b->barrier_probe,
5732 				    "skip purge"));
5733 			}
5734 		} else
5735 			bp = &b->barrier_next;
5736 	}
5737 
5738 	mutex_exit(&scsi_hba_barrier_mutex);
5739 }
5740 
5741 /*
5742  * LUN-change processing daemons: processing occurs in two stages:
5743  *
5744  * Stage 1:	Daemon waits for a lunchg1 queued scsi_pkt, dequeues the pkt,
5745  *		forms the path, completes the scsi_pkt (pkt_comp), and
5746  *		queues the path for stage 2 processing. The use of stage 1
5747  *		avoids issues related to memory allocation in interrupt context
5748  *		(scsi_hba_pkt_comp()). We delay the pkt_comp completion until
5749  *		after lunchg1 processing forms the path for stage 2 - this is
5750  *		done to prevent the target driver from detaching until the
5751  *		path formation is complete (driver with outstanding commands
5752  *		should not detach).
5753  *
5754  * Stage 2:	Daemon waits for a lunchg2 queued request, dequeues the
5755  *		request, and opens the path using ldi_open_by_name(). The
5756  *		path opened uses a special "@taddr,*" unit address that will
5757  *		trigger lun enumeration in scsi_hba_bus_configone(). We
5758  *		trigger lun enumeration in stage 2 to avoid problems when
5759  *		initial ASC/ASCQ trigger occurs during discovery.
5760  */
5761 /*ARGSUSED*/
5762 static void
5763 scsi_lunchg1_daemon(void *arg)
5764 {
5765 	callb_cpr_t		cprinfo;
5766 	struct scsi_pkt		*pkt;
5767 	scsi_hba_tran_t		*tran;
5768 	dev_info_t		*self;
5769 	struct scsi_device	*sd;
5770 	char			*ua, *p;
5771 	char			taddr[SCSI_MAXNAMELEN];
5772 	char			path[MAXPATHLEN];
5773 	struct scsi_lunchg2	*lunchg2;
5774 
5775 	CALLB_CPR_INIT(&cprinfo, &scsi_lunchg1_mutex,
5776 	    callb_generic_cpr, "scsi_lunchg1_daemon");
5777 	mutex_enter(&scsi_lunchg1_mutex);
5778 	for (;;) {
5779 		pkt = scsi_lunchg1_list;
5780 		if (pkt == NULL) {
5781 			/* All lunchg1 processing requests serviced, wait. */
5782 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5783 			(void) cv_wait(&scsi_lunchg1_cv,
5784 			    &scsi_lunchg1_mutex);
5785 			CALLB_CPR_SAFE_END(&cprinfo, &scsi_lunchg1_mutex);
5786 			continue;
5787 		}
5788 
5789 		/* Unlink and perform lunchg1 processing on pkt. */
5790 		scsi_lunchg1_list = pkt->pkt_stmp;
5791 
5792 		/* Determine initiator port (self) from the pkt_address. */
5793 		tran = pkt->pkt_address.a_hba_tran;
5794 		ASSERT(tran && tran->tran_tgtmap && tran->tran_iport_dip);
5795 		self = tran->tran_iport_dip;
5796 
5797 		/*
5798 		 * Determine scsi_devie from pkt_address (depends on
5799 		 * SCSI_HBA_ADDR_COMPLEX).
5800 		 */
5801 		sd = scsi_address_device(&(pkt->pkt_address));
5802 		ASSERT(sd);
5803 		if (sd == NULL) {
5804 			(*pkt->pkt_comp)(pkt);
5805 			continue;
5806 		}
5807 
5808 		/* Determine unit-address from scsi_device. */
5809 		ua = scsi_device_unit_address(sd);
5810 
5811 		/* Extract taddr from the unit-address. */
5812 		for (p = taddr; (*ua != ',') && (*ua != '\0'); )
5813 			*p++ = *ua++;
5814 		*p = '\0';			/* NULL terminate taddr */
5815 
5816 		/*
5817 		 * Form path using special "@taddr,*" notation to trigger
5818 		 * lun enumeration.
5819 		 */
5820 		(void) ddi_pathname(self, path);
5821 		(void) strcat(path, "/luns@");
5822 		(void) strcat(path, taddr);
5823 		(void) strcat(path, ",*");
5824 
5825 		/*
5826 		 * Now that we have the path, complete the pkt that
5827 		 * triggered lunchg1 processing.
5828 		 */
5829 		(*pkt->pkt_comp)(pkt);
5830 
5831 		/* Allocate element for stage2 processing queue. */
5832 		lunchg2 = kmem_alloc(sizeof (*lunchg2), KM_SLEEP);
5833 		lunchg2->lunchg2_path = strdup(path);
5834 
5835 		/* Queue and dispatch to stage 2. */
5836 		SCSI_HBA_LOG((_LOG(2), self, NULL,
5837 		    "lunchg stage1: queue %s", lunchg2->lunchg2_path));
5838 		mutex_enter(&scsi_lunchg2_mutex);
5839 		lunchg2->lunchg2_next = scsi_lunchg2_list;
5840 		scsi_lunchg2_list = lunchg2;
5841 		if (lunchg2->lunchg2_next == NULL)
5842 			(void) cv_signal(&scsi_lunchg2_cv);
5843 		mutex_exit(&scsi_lunchg2_mutex);
5844 	}
5845 }
5846 
5847 /*ARGSUSED*/
5848 static void
5849 scsi_lunchg2_daemon(void *arg)
5850 {
5851 	callb_cpr_t		cprinfo;
5852 	struct scsi_lunchg2	*lunchg2;
5853 	ldi_ident_t		li;
5854 	ldi_handle_t		lh;
5855 
5856 	CALLB_CPR_INIT(&cprinfo, &scsi_lunchg2_mutex,
5857 	    callb_generic_cpr, "scsi_lunchg2_daemon");
5858 
5859 	li = ldi_ident_from_anon();
5860 	mutex_enter(&scsi_lunchg2_mutex);
5861 	for (;;) {
5862 		lunchg2 = scsi_lunchg2_list;
5863 		if (lunchg2 == NULL) {
5864 			/* All lunchg2 processing requests serviced, wait. */
5865 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5866 			(void) cv_wait(&scsi_lunchg2_cv,
5867 			    &scsi_lunchg2_mutex);
5868 			CALLB_CPR_SAFE_END(&cprinfo, &scsi_lunchg2_mutex);
5869 			continue;
5870 		}
5871 
5872 		/* Unlink and perform lunchg2 processing on pkt. */
5873 		scsi_lunchg2_list = lunchg2->lunchg2_next;
5874 
5875 		/*
5876 		 * Open and close the path to trigger lun enumeration.  We
5877 		 * don't expect the open to succeed, but we do expect code in
5878 		 * scsi_hba_bus_configone() to trigger lun enumeration.
5879 		 */
5880 		SCSI_HBA_LOG((_LOG(2), NULL, NULL,
5881 		    "lunchg stage2: open %s", lunchg2->lunchg2_path));
5882 		if (ldi_open_by_name(lunchg2->lunchg2_path,
5883 		    FREAD, kcred, &lh, li) == 0)
5884 			(void) ldi_close(lh, FREAD, kcred);
5885 
5886 		/* Free path and linked element. */
5887 		strfree(lunchg2->lunchg2_path);
5888 		kmem_free(lunchg2, sizeof (*lunchg2));
5889 	}
5890 }
5891 
5892 /*
5893  * Enumerate a child at the specified @addr. If a device exists @addr then
5894  * ensure that we have the appropriately named devinfo node for it. Name is
5895  * NULL in the bus_config_all case. This routine has no knowledge of the
5896  * format of an @addr string or associated addressing properties.
5897  *
5898  * The caller must guarantee that there is an open scsi_hba_devi_enter on the
5899  * parent. We return the scsi_device structure for the child device. This
5900  * scsi_device structure is valid until the caller scsi_hba_devi_exit the
5901  * parent. The caller can add do ndi_hold_devi of the child prior to the
5902  * scsi_hba_devi_exit to extend the validity of the child.
5903  *
5904  * In some cases the returned scsi_device structure may be used to drive
5905  * additional SCMD_REPORT_LUNS operations by bus_config_all callers.
5906  *
5907  * The first operation performed is to see if there is a dynamic SID nodes
5908  * already attached at the specified "name@addr". This is the fastpath
5909  * case for resolving a reference to a node that has already been created.
5910  * All other references are serialized for a given @addr prior to probing
5911  * to determine the type of device, if any, at the specified @addr.
5912  * If no device is present then NDI_FAILURE is returned. The fact that a
5913  * device does not exist may be determined via the barrier/probe cache,
5914  * minimizing the probes of non-existent devices.
5915  *
5916  * When there is a device present the dynamic SID node is created based on
5917  * the device found. If a driver.conf node exists for the same @addr it
5918  * will either merge into the dynamic SID node (if the SID node bound to
5919  * that driver), or exist independently. To prevent the actions of one driver
5920  * causing side effects in another, code prevents multiple SID nodes from
5921  * binding to the same "@addr" at the same time. There is autodetach code
5922  * to allow one device to be replaced with another at the same @addr for
5923  * slot addressed SCSI bus implementations (SPI). For compatibility with
5924  * legacy driver.conf behavior, the code does not prevent multiple driver.conf
5925  * nodes from attaching to the same @addr at the same time.
5926  *
5927  * This routine may have the side effect of creating nodes for devices other
5928  * than the one being sought. It is possible that there is a different type of
5929  * target device at that target/lun address than we were asking for. In that
5930  * It is the caller's responsibility to determine whether the device we found,
5931  * if any, at the specified address, is the one it really wanted.
5932  */
5933 static struct scsi_device *
5934 scsi_device_config(dev_info_t *self, char *name, char *addr, scsi_enum_t se,
5935     int *circp, int *ppi)
5936 {
5937 	dev_info_t		*child = NULL;
5938 	dev_info_t		*probe = NULL;
5939 	struct scsi_device	*sdchild;
5940 	struct scsi_device	*sdprobe;
5941 	dev_info_t		*dsearch;
5942 	mdi_pathinfo_t		*psearch;
5943 	major_t			major;
5944 	int			sp;
5945 	int			pi = 0;
5946 	int			wait_msg = scsi_hba_wait_msg;
5947 	int			chg;
5948 
5949 	ASSERT(self && addr && DEVI_BUSY_OWNED(self));
5950 
5951 	SCSI_HBA_LOG((_LOG(4), self, NULL, "%s@%s wanted",
5952 	    name ? name : "", addr));
5953 
5954 	/* playing with "probe" node name is dangerous */
5955 	if (name && (strcmp(name, "probe") == 0))
5956 		return (NULL);
5957 
5958 	/*
5959 	 * NOTE: use 'goto done;' or 'goto fail;'. There should only be one
5960 	 * 'return' statement from here to the end of the function - the one
5961 	 * on the last line of the function.
5962 	 */
5963 
5964 	/*
5965 	 * Fastpath: search to see if we are requesting a named SID node that
5966 	 * already exists (we already created) - probe node does not count.
5967 	 * scsi_hba_find_child() does not hold the returned devinfo node, but
5968 	 * this is OK since the caller has a scsi_hba_devi_enter on the
5969 	 * attached parent HBA (self). The caller is responsible for attaching
5970 	 * and placing a hold on the child (directly via ndi_hold_devi or
5971 	 * indirectly via ndi_busop_bus_config) before doing an
5972 	 * scsi_hba_devi_exit on the parent.
5973 	 *
5974 	 * NOTE: This fastpath prevents detecting a driver binding change
5975 	 * (autodetach) if the same nodename is used for old and new binding.
5976 	 */
5977 	/* first call is with init set */
5978 	(void) scsi_hba_find_child(self, name, addr,
5979 	    1, &dsearch, NULL, &pi);
5980 	if (dsearch && scsi_hba_dev_is_sid(dsearch) &&
5981 	    !scsi_hba_devi_is_barrier(dsearch)) {
5982 		SCSI_HBA_LOG((_LOG(4), NULL, dsearch,
5983 		    "%s@%s devinfo fastpath", name ? name : "", addr));
5984 		child = dsearch;
5985 		goto done;
5986 	}
5987 
5988 	/*
5989 	 * Create a barrier devinfo node used to "probe" the device with. We
5990 	 * need to drive this node to DS_INITIALIZED so that the
5991 	 * DDI_CTLOPS_INITCHILD has occurred, bringing the SCSA transport to
5992 	 * a state useable state for issuing our "probe" commands. We establish
5993 	 * this barrier node with a node name of "probe" and compatible
5994 	 * property of "scsiprobe". The compatible property must be associated
5995 	 * in /etc/driver_aliases with a scsi target driver available in the
5996 	 * root file system (sd).
5997 	 *
5998 	 * The "probe" that we perform on the barrier node, after it is
5999 	 * DS_INITIALIZED, is used to find the information needed to create a
6000 	 * dynamic devinfo (SID) node. This "probe" is separate from the
6001 	 * probe(9E) call associated with the transition of a node from
6002 	 * DS_INITIALIZED to DS_PROBED. The probe(9E) call that eventually
6003 	 * occurs against the created SID node should find ddi_dev_is_sid and
6004 	 * just return DDI_PROBE_DONTCARE.
6005 	 *
6006 	 * Trying to avoid the use of a barrier node is not a good idea
6007 	 * because we may have an HBA driver that uses generic bus_config
6008 	 * (this code) but implements its own DDI_CTLOPS_INITCHILD with side
6009 	 * effects that we can't duplicate (such as the ATA nexus driver).
6010 	 *
6011 	 * The probe/barrier node plays an integral part of the locking scheme.
6012 	 * The objective is to single thread probes of the same device (same
6013 	 * @addr) while allowing parallelism for probes of different devices
6014 	 * with the same parent. At this point we are serialized on our self.
6015 	 * For parallelism we will need to release our self. Prior to release
6016 	 * we construct a barrier for probes of the same device to serialize
6017 	 * against. The "probe@addr" node acts as this barrier. An entering
6018 	 * thread must wait until the probe node does not exist - it can then
6019 	 * create and link the probe node - dropping the HBA (self) lock after
6020 	 * the node is linked and visible (after ddi_initchild). A side effect
6021 	 * of this is that transports should not "go over the wire" (i.e. do
6022 	 * things that incur significant delays) until after tran_target_init.
6023 	 * This means that the first "over the wire" operation should occur
6024 	 * at tran_target_probe time - when things are running in parallel
6025 	 * again.
6026 	 *
6027 	 * If the probe node exists then another probe with the same @addr is
6028 	 * in progress, we must wait until there is no probe in progress
6029 	 * before proceeding, and when we proceed we must continue to hold the
6030 	 * HBA (self) until we have linked a new probe node as a barrier.
6031 	 *
6032 	 * When a device is found to *not* exist, its probe/barrier node may be
6033 	 * marked with DEVICE_REMOVED with node deletion scheduled for some
6034 	 * future time (seconds). This asynchronous deletion allows the
6035 	 * framework to detect repeated requests to the same non-existent
6036 	 * device and avoid overhead associated with contacting a non-existent
6037 	 * device again and again.
6038 	 */
6039 	for (;;) {
6040 		/*
6041 		 * Search for probe node - they should only exist as devinfo
6042 		 * nodes.
6043 		 */
6044 		(void) scsi_hba_find_child(self, "probe", addr,
6045 		    0, &probe, &psearch, NULL);
6046 		if (probe == NULL) {
6047 			if (psearch)
6048 				SCSI_HBA_LOG((_LOG(2), self,
6049 				    mdi_pi_get_client(psearch),
6050 				    "???? @%s 'probe' search found "
6051 				    "pathinfo: %p", addr, (void *)psearch));
6052 			break;
6053 		}
6054 
6055 		/*
6056 		 * The barrier node may cache the non-existence of a device
6057 		 * by leaving the barrier node in place (with
6058 		 * DEVI_DEVICE_REMOVED flag set ) for some amount of time after
6059 		 * the failure of a probe. This flag is used to fail
6060 		 * additional probes until the barrier probe node is deleted,
6061 		 * which will occur from a timeout some time after a failed
6062 		 * probe. The failed probe will use DEVI_SET_DEVICE_REMOVED
6063 		 * and schedule probe node deletion from a timeout. The callers
6064 		 * scsi_hba_devi_exit on the way out of the first failure will
6065 		 * do the cv_broadcast associated with the cv_wait below - this
6066 		 * handles threads that wait prior to DEVI_DEVICE_REMOVED being
6067 		 * set.
6068 		 */
6069 		if (DEVI_IS_DEVICE_REMOVED(probe)) {
6070 			SCSI_HBA_LOG((_LOG(3), NULL, probe,
6071 			    "detected probe DEVICE_REMOVED"));
6072 			probe = NULL;	/* deletion already scheduled */
6073 			goto fail;
6074 		}
6075 
6076 		/*
6077 		 * Drop the lock on the HBA (self) and wait until the probe in
6078 		 * progress has completed. A changes in the sibling list from
6079 		 * removing the probe node will cause cv_wait to return
6080 		 * (scsi_hba_devi_exit does the cv_broadcast).
6081 		 */
6082 		if (wait_msg) {
6083 			wait_msg--;
6084 			SCSI_HBA_LOG((_LOG(2), NULL, probe,
6085 			    "exists, probe already in progress: %s", wait_msg ?
6086 			    "waiting..." : "last msg, but still waiting..."));
6087 		}
6088 
6089 		/*
6090 		 * NOTE: we could avoid rare case of one second delay by
6091 		 * implementing scsi_hba_devi_exit_and_wait based on
6092 		 * ndi/mdi_devi_exit_and_wait (and consider switching devcfg.c
6093 		 * code to use these ndi/mdi interfaces too).
6094 		 */
6095 		scsi_hba_devi_exit(self, *circp);
6096 		mutex_enter(&DEVI(self)->devi_lock);
6097 		(void) cv_timedwait(&DEVI(self)->devi_cv,
6098 		    &DEVI(self)->devi_lock,
6099 		    ddi_get_lbolt() + drv_usectohz(MICROSEC));
6100 		mutex_exit(&DEVI(self)->devi_lock);
6101 		scsi_hba_devi_enter(self, circp);
6102 	}
6103 	ASSERT(probe == NULL);
6104 
6105 	/*
6106 	 * Search to see if we are requesting a SID node that already exists.
6107 	 * We hold the HBA (self) and there is not another probe in progress at
6108 	 * the same @addr. scsi_hba_find_child() does not hold the returned
6109 	 * devinfo node but this is OK since we hold the HBA (self).
6110 	 */
6111 	if (name) {
6112 		(void) scsi_hba_find_child(self, name, addr,
6113 		    1, &dsearch, NULL, &pi);
6114 		if (dsearch && scsi_hba_dev_is_sid(dsearch)) {
6115 			SCSI_HBA_LOG((_LOG(4), NULL, dsearch,
6116 			    "%s@%s probe devinfo fastpath",
6117 			    name ? name : "", addr));
6118 			child = dsearch;
6119 			goto done;
6120 		}
6121 	}
6122 
6123 	/*
6124 	 * We are looking for a SID node that does not exist or a driver.conf
6125 	 * node.
6126 	 *
6127 	 * To avoid probe side effects, before we probe the device at the
6128 	 * specified address we need to check to see if there is already an
6129 	 * initialized child "@addr".
6130 	 *
6131 	 * o If we find an initialized SID child and name is NULL or matches
6132 	 *   the name or the name of the attached driver then we return the
6133 	 *   existing node.
6134 	 *
6135 	 * o If we find a non-matching SID node, we will attempt to autodetach
6136 	 *   and remove the node in preference to our new node.
6137 	 *
6138 	 * o If SID node found does not match and can't be autodetached, we
6139 	 *   fail: we only allow one SID node at an address.
6140 	 *
6141 	 * NOTE: This code depends on SID nodes showing up prior to
6142 	 * driver.conf nodes in the sibling list.
6143 	 */
6144 	for (;;) {
6145 		/* first NULL name call is with init set */
6146 		(void) scsi_hba_find_child(self, NULL, addr,
6147 		    1, &dsearch, NULL, &pi);
6148 		if (dsearch == NULL)
6149 			break;
6150 		ASSERT(!scsi_hba_devi_is_barrier(dsearch));
6151 
6152 		/*
6153 		 * To detect changes in driver binding that should attempt
6154 		 * autodetach we determine the major number of the driver
6155 		 * that should currently be associated with the device based
6156 		 * on the compatible property.
6157 		 */
6158 		major = DDI_MAJOR_T_NONE;
6159 		if (scsi_hba_dev_is_sid(dsearch))
6160 			major = ddi_compatible_driver_major(dsearch, NULL);
6161 		if ((major == DDI_MAJOR_T_NONE) && (name == NULL))
6162 			major = ddi_driver_major(dsearch);
6163 
6164 		if ((scsi_hba_dev_is_sid(dsearch) ||
6165 		    (i_ddi_node_state(dsearch) >= DS_INITIALIZED)) &&
6166 		    ((name == NULL) ||
6167 		    (strcmp(ddi_node_name(dsearch), name) == 0) ||
6168 		    (strcmp(ddi_driver_name(dsearch), name) == 0)) &&
6169 		    (major == ddi_driver_major(dsearch))) {
6170 			SCSI_HBA_LOG((_LOG(3), NULL, dsearch,
6171 			    "already attached @addr"));
6172 			child = dsearch;
6173 			goto done;
6174 		}
6175 
6176 		if (!scsi_hba_dev_is_sid(dsearch))
6177 			break;			/* driver.conf node */
6178 
6179 		/*
6180 		 * Implement autodetach of SID node for situations like a
6181 		 * previously "scsinodev" LUN0 coming into existence (or a
6182 		 * disk/tape on an SPI transport at same addr but never both
6183 		 * powered on at the same time). Try to autodetach the existing
6184 		 * SID node @addr. If that works, search again - otherwise fail.
6185 		 */
6186 		SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6187 		    "looking for %s@%s: SID @addr exists, autodetach",
6188 		    name ? name : "", addr));
6189 		if (!scsi_hba_remove_node(dsearch)) {
6190 			SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6191 			    "autodetach @%s failed: fail %s@%s",
6192 			    addr, name ? name : "", addr));
6193 			goto fail;
6194 		}
6195 		SCSI_HBA_LOG((_LOG(2), self, NULL, "autodetach @%s OK", addr));
6196 	}
6197 
6198 	/*
6199 	 * We will be creating a new SID node, allocate probe node
6200 	 * used to find out information about the device located @addr.
6201 	 * The probe node also acts as a barrier against additional
6202 	 * configuration at the same address, and in the case of non-existent
6203 	 * devices it will (for some amount of time) avoid re-learning that
6204 	 * the device does not exist on every reference. Once the probe
6205 	 * node is DS_LINKED we can drop the HBA (self).
6206 	 *
6207 	 * The probe node is allocated as a hidden node so that it does not
6208 	 * show up in devinfo snapshots.
6209 	 */
6210 	ndi_devi_alloc_sleep(self, "probe",
6211 	    (se == SE_HP) ? DEVI_SID_HP_HIDDEN_NODEID : DEVI_SID_HIDDEN_NODEID,
6212 	    &probe);
6213 	ASSERT(probe);
6214 	ndi_flavor_set(probe, SCSA_FLAVOR_SCSI_DEVICE);
6215 
6216 	/*
6217 	 * Decorate the probe node with the property representation of @addr
6218 	 * unit-address string prior to initchild so that initchild can
6219 	 * construct the name of the node from properties and tran_tgt_init
6220 	 * implementation can determine what LUN is being referenced.
6221 	 *
6222 	 * If the addr specified has incorrect syntax (busconfig one of bogus
6223 	 * /devices path) then scsi_hba_ua_set can fail.  If the address
6224 	 * is not understood by the SCSA HBA driver then this operation will
6225 	 * work, but tran_tgt_init may still fail (for example the HBA
6226 	 * driver may not support secondary functions).
6227 	 */
6228 	if (scsi_hba_ua_set(addr, probe, NULL) == 0) {
6229 		SCSI_HBA_LOG((_LOG(2), NULL, probe,
6230 		    "@%s failed scsi_hba_ua_set", addr));
6231 		goto fail;
6232 	}
6233 
6234 	/*
6235 	 * Set the class property to "scsi". This is sufficient to distinguish
6236 	 * the node for HBAs that have multiple classes of children (like uata
6237 	 * - which has "dada" class for ATA children and "scsi" class for
6238 	 * ATAPI children) and may not use our scsi_busctl_initchild()
6239 	 * implementation. We also add a "compatible" property of "scsiprobe"
6240 	 * to select the probe driver.
6241 	 */
6242 	if ((ndi_prop_update_string(DDI_DEV_T_NONE, probe,
6243 	    "class", "scsi") != DDI_PROP_SUCCESS) ||
6244 	    (ndi_prop_update_string_array(DDI_DEV_T_NONE, probe,
6245 	    "compatible", &compatible_probe, 1) != DDI_PROP_SUCCESS)) {
6246 		SCSI_HBA_LOG((_LOG(1), NULL, probe,
6247 		    "@%s failed node decoration", addr));
6248 		goto fail;
6249 	}
6250 
6251 	/*
6252 	 * Promote probe node to DS_INITIALIZED so that transport can be used
6253 	 * for scsi_probe. After this the node is linked and visible as a
6254 	 * barrier for serialization of other @addr operations.
6255 	 *
6256 	 * NOTE: If we attached the probe node, we could get rid of
6257 	 * uninit_prevent.
6258 	 */
6259 	if (ddi_initchild(self, probe) != DDI_SUCCESS) {
6260 		SCSI_HBA_LOG((_LOG(2), NULL, probe,
6261 		    "@%s failed initchild", addr));
6262 
6263 		/* probe node will be removed in fail exit path */
6264 		goto fail;
6265 	}
6266 
6267 	/* get the scsi_device structure of the probe node */
6268 	sdprobe = ddi_get_driver_private(probe);
6269 	ASSERT(sdprobe);
6270 
6271 	/*
6272 	 * Do scsi_probe. The probe node is linked and visible as a barrier.
6273 	 * We prevent uninitialization of the probe node and drop our HBA (self)
6274 	 * while we run scsi_probe() of this "@addr". This allows the framework
6275 	 * to support multiple scsi_probes for different devices attached to
6276 	 * the same HBA (self) in parallel. We prevent node demotion of the
6277 	 * probe node from DS_INITIALIZED by setting sd_uninit_prevent. The
6278 	 * probe node can not be successfully demoted below DS_INITIALIZED
6279 	 * (scsi_busctl_uninitchild will fail) until we zero sd_uninit_prevent
6280 	 * as we are freeing the node via scsi_hba_remove_node(probe).
6281 	 */
6282 	sdprobe->sd_uninit_prevent++;
6283 	scsi_hba_devi_exit(self, *circp);
6284 	sp = scsi_probe(sdprobe, SLEEP_FUNC);
6285 
6286 	/* Introduce a small delay here to increase parallelism. */
6287 	delay_random(5);
6288 
6289 	if (sp == SCSIPROBE_EXISTS) {
6290 		/*
6291 		 * For a device that exists, while still running in parallel,
6292 		 * also get identity information from device. This is done
6293 		 * separate from scsi_probe/tran_tgt_probe/scsi_hba_probe
6294 		 * since the probe code path may still be used for HBAs
6295 		 * that don't use common bus_config services (we don't want
6296 		 * to expose that code path to a behavior change). This
6297 		 * operation is called 'identity' to avoid confusion with
6298 		 * deprecated identify(9E).
6299 		 *
6300 		 * Future: We may eventually want to allow HBA customization via
6301 		 * scsi_identity/tran_tgt_identity/scsi_device_identity, but for
6302 		 * now we just scsi_device_identity.
6303 		 *
6304 		 * The identity operation will establish additional properties
6305 		 * on the probe node related to device identity:
6306 		 *
6307 		 *	"inquiry-page-80"	byte array of SCSI page 80
6308 		 *	"inquiry-page-83"	byte array of SCSI page 83
6309 		 *
6310 		 * These properties will be used to generate a devid
6311 		 * (ddi_devid_scsi_encode) and guid - and to register
6312 		 * (ddi_devid_register) a devid for the device.
6313 		 *
6314 		 * If identify fails (non-zero return), the we had allocation
6315 		 * problems or the device returned inconsistent results then
6316 		 * we pretend that device does not exist.
6317 		 */
6318 		if (scsi_device_identity(sdprobe, SLEEP_FUNC)) {
6319 			if (ndi_dev_is_hotplug_node(probe))
6320 				SCSI_HBA_LOG((_LOG(WARN), NULL, probe,
6321 				    "enumeration failed during identity"));
6322 			else
6323 				SCSI_HBA_LOG((_LOG(2), NULL, probe,
6324 				    "enumeration failed during identity"));
6325 			sp = SCSIPROBE_FAILURE;
6326 		}
6327 
6328 		/*
6329 		 * Future: Is there anything more we can do here to help avoid
6330 		 * serialization on iport parent during scsi_device attach(9E)?
6331 		 */
6332 	}
6333 	scsi_hba_devi_enter(self, circp);
6334 	sdprobe->sd_uninit_prevent--;
6335 
6336 	if (sp != SCSIPROBE_EXISTS) {
6337 		if (ndi_dev_is_hotplug_node(probe))
6338 			SCSI_HBA_LOG((_LOG(WARN), NULL, probe,
6339 			    "enumeration failed during probe"));
6340 		else
6341 			SCSI_HBA_LOG((_LOG(2), NULL, probe,
6342 			    "enumeration failed durning probe"));
6343 
6344 		if (scsi_hba_barrier_timeout) {
6345 			/*
6346 			 * Target does not exist. Mark the barrier probe node
6347 			 * as DEVICE_REMOVED and schedule an asynchronous
6348 			 * deletion of the node in scsi_hba_barrier_timeout
6349 			 * seconds. We keep our hold on the probe node
6350 			 * until we are ready perform the asynchronous node
6351 			 * deletion.
6352 			 */
6353 			SCSI_HBA_LOG((_LOG(3), NULL, probe,
6354 			    "set probe DEVICE_REMOVED"));
6355 			mutex_enter(&DEVI(probe)->devi_lock);
6356 			DEVI_SET_DEVICE_REMOVED(probe);
6357 			mutex_exit(&DEVI(probe)->devi_lock);
6358 
6359 			scsi_hba_barrier_add(probe, scsi_hba_barrier_timeout);
6360 			probe = NULL;
6361 		}
6362 		goto fail;
6363 	}
6364 
6365 	/* Create the child node from the inquiry data in the probe node. */
6366 	if ((child = scsi_device_configchild(self, addr, se, sdprobe,
6367 	    circp, &pi)) == NULL) {
6368 		/*
6369 		 * This may fail because there was no driver binding identified
6370 		 * via driver_alias. We may still have a conf node.
6371 		 */
6372 		if (name) {
6373 			(void) scsi_hba_find_child(self, name, addr,
6374 			    0, &child, NULL, &pi);
6375 			if (child)
6376 				SCSI_HBA_LOG((_LOG(2), NULL, child,
6377 				    "using driver.conf driver binding"));
6378 		}
6379 		if (child == NULL) {
6380 			SCSI_HBA_LOG((_LOG(2), NULL, probe,
6381 			    "device not configured"));
6382 			goto fail;
6383 		}
6384 	}
6385 
6386 	/*
6387 	 * Transfer the inquiry data from the probe node to the child
6388 	 * SID node to avoid an extra scsi_probe. Callers depend on
6389 	 * established inquiry data for the returned scsi_device.
6390 	 */
6391 	sdchild = ddi_get_driver_private(child);
6392 	if (sdchild && (sdchild->sd_inq == NULL)) {
6393 		sdchild->sd_inq = sdprobe->sd_inq;
6394 		sdprobe->sd_inq = NULL;
6395 	}
6396 
6397 	/*
6398 	 * If we are doing a bus_configone and the node we created has the
6399 	 * wrong node and driver name then switch the return result to a
6400 	 * driver.conf node with the correct name - if such a node exists.
6401 	 */
6402 	if (name && (strcmp(ddi_node_name(child), name) != 0) &&
6403 	    (strcmp(ddi_driver_name(child), name) != 0)) {
6404 		(void) scsi_hba_find_child(self, name, addr,
6405 		    0, &dsearch, NULL, &pi);
6406 		if (dsearch == NULL) {
6407 			SCSI_HBA_LOG((_LOG(2), NULL, child,
6408 			    "wrong device configured %s@%s", name, addr));
6409 			/*
6410 			 * We can't remove when modrootloaded == 0 in case
6411 			 * boot-device a uses generic name and
6412 			 * scsi_hba_nodename_compatible_get() returned a
6413 			 * legacy binding-set driver oriented name.
6414 			 */
6415 			if (modrootloaded) {
6416 				(void) scsi_hba_remove_node(child);
6417 				child = NULL;
6418 				goto fail;
6419 			}
6420 		} else {
6421 			SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6422 			    "device configured, but switching to driver.conf"));
6423 			child = dsearch;
6424 		}
6425 	}
6426 
6427 	/* get the scsi_device structure from the node */
6428 	SCSI_HBA_LOG((_LOG(3), NULL, child, "device configured"));
6429 
6430 	if (child) {
6431 done:		ASSERT(child);
6432 		sdchild = ddi_get_driver_private(child);
6433 		ASSERT(sdchild);
6434 		/*
6435 		 * We may have ended up here after promotion of a previously
6436 		 * demoted node, where demotion deleted sd_inq data in
6437 		 * scsi_busctl_uninitchild.  We redo the scsi_probe() to
6438 		 * reestablish sd_inq.  We also want to redo the scsi_probe
6439 		 * for devices are currently device_isremove in order to
6440 		 * detect new device_insert.
6441 		 */
6442 		if ((sdchild->sd_inq == NULL) ||
6443 		    ndi_devi_device_isremoved(child)) {
6444 
6445 			/* hotplug_node can only be revived via hotplug. */
6446 			if ((se == SE_HP) || !ndi_dev_is_hotplug_node(child)) {
6447 				SCSI_HBA_LOG((_LOG(3), NULL, child,
6448 				    "scsi_probe() demoted devinfo"));
6449 
6450 				sp = scsi_probe(sdchild, SLEEP_FUNC);
6451 
6452 				if (sp == SCSIPROBE_EXISTS) {
6453 					ASSERT(sdchild->sd_inq);
6454 
6455 					/*
6456 					 * Devinfo child exists and we are
6457 					 * talking to the device, report
6458 					 * reinsert and note if this was a
6459 					 * new reinsert.
6460 					 */
6461 					chg = ndi_devi_device_insert(child);
6462 					SCSI_HBA_LOG((_LOGCFG, self, NULL,
6463 					    "devinfo %s@%s device_reinsert%s",
6464 					    name ? name : "", addr,
6465 					    chg ? "" : "ed already"));
6466 				} else {
6467 					if (se == SE_HP)
6468 						SCSI_HBA_LOG((_LOG(WARN),
6469 						    NULL, child,
6470 						    "enumeration failed during "
6471 						    "reprobe"));
6472 					else
6473 						SCSI_HBA_LOG((_LOG(2),
6474 						    NULL, child,
6475 						    "enumeration failed during "
6476 						    "reprobe"));
6477 
6478 					chg = ndi_devi_device_remove(child);
6479 					SCSI_HBA_LOG((_LOG(2), NULL, child,
6480 					    "%s device_remove%s",
6481 					    (sp > (sizeof (scsi_probe_ascii) /
6482 					    sizeof (scsi_probe_ascii[0]))) ?
6483 					    "UNKNOWN" : scsi_probe_ascii[sp],
6484 					    chg ? "" : "ed already"));
6485 
6486 					child = NULL;
6487 					sdchild = NULL;
6488 				}
6489 			} else {
6490 				SCSI_HBA_LOG((_LOG(2), NULL, child,
6491 				    "no reprobe"));
6492 
6493 				child = NULL;
6494 				sdchild = NULL;
6495 			}
6496 		}
6497 	} else {
6498 fail:		ASSERT(child == NULL);
6499 		sdchild = NULL;
6500 	}
6501 	if (probe) {
6502 		/*
6503 		 * Clean up probe node, destroying node if uninit_prevent
6504 		 * it is going to zero. Destroying the probe node (deleting
6505 		 * from the sibling list) will wake up any people waiting on
6506 		 * the probe node barrier.
6507 		 */
6508 		SCSI_HBA_LOG((_LOG(4), NULL, probe, "remove probe"));
6509 		if (!scsi_hba_remove_node(probe)) {
6510 			/*
6511 			 * Probe node removal should not fail, but if it
6512 			 * does we hand that responsibility over to the
6513 			 * async barrier deletion thread - other references
6514 			 * to the same unit-address can hang until the
6515 			 * probe node delete completes.
6516 			 */
6517 			SCSI_HBA_LOG((_LOG(4), NULL, probe,
6518 			    "remove probe failed, go async"));
6519 			scsi_hba_barrier_add(probe, 1);
6520 		}
6521 		probe = NULL;
6522 	}
6523 
6524 	/*
6525 	 * If we successfully resolved via a pathinfo node, we need to find
6526 	 * the pathinfo node and ensure that it is online (if possible). This
6527 	 * is done for the case where the device was open when
6528 	 * scsi_device_unconfig occurred, so mdi_pi_free did not occur. If the
6529 	 * device has now been reinserted, we want the path back online.
6530 	 * NOTE: This needs to occur after destruction of the probe node to
6531 	 * avoid ASSERT related to two nodes at the same unit-address.
6532 	 */
6533 	if (sdchild && pi && (probe == NULL)) {
6534 		ASSERT(MDI_PHCI(self));
6535 
6536 		(void) scsi_hba_find_child(self, NULL, addr,
6537 		    0, &dsearch, &psearch, NULL);
6538 		ASSERT((psearch == NULL) ||
6539 		    (mdi_pi_get_client(psearch) == child));
6540 
6541 		if (psearch && mdi_pi_device_isremoved(psearch)) {
6542 			/*
6543 			 * Verify that we can talk to the device, and if
6544 			 * so note if this is a new device_insert.
6545 			 *
6546 			 * NOTE: We depend on mdi_path_select(), when given
6547 			 * a specific path_instance, to select that path
6548 			 * even if the path is offline.
6549 			 *
6550 			 * NOTE: A Client node is not ndi_dev_is_hotplug_node().
6551 			 */
6552 			if (se == SE_HP) {
6553 				SCSI_HBA_LOG((_LOG(3), NULL, child,
6554 				    "%s scsi_probe() demoted pathinfo",
6555 				    mdi_pi_spathname(psearch)));
6556 
6557 				sp = scsi_hba_probe_pi(sdchild, SLEEP_FUNC, pi);
6558 
6559 				if (sp == SCSIPROBE_EXISTS) {
6560 					/*
6561 					 * Pathinfo child exists and we are
6562 					 * talking to the device, report
6563 					 * reinsert and note if this
6564 					 * was a new reinsert.
6565 					 */
6566 					chg = mdi_pi_device_insert(psearch);
6567 					SCSI_HBA_LOG((_LOGCFG, self, NULL,
6568 					    "pathinfo %s device_reinsert%s",
6569 					    mdi_pi_spathname(psearch),
6570 					    chg ? "" : "ed already"));
6571 
6572 					if (chg)
6573 						(void) mdi_pi_online(psearch,
6574 						    0);
6575 
6576 				} else {
6577 					SCSI_HBA_LOG((_LOG(WARN), NULL, child,
6578 					    "%s enumeration failed "
6579 					    "during reprobe",
6580 					    mdi_pi_spathname(psearch)));
6581 
6582 					child = NULL;
6583 					sdchild = NULL;
6584 				}
6585 
6586 			} else {
6587 				SCSI_HBA_LOG((_LOG(2), NULL, child,
6588 				    "%s no reprobe",
6589 				    mdi_pi_spathname(psearch)));
6590 
6591 				child = NULL;
6592 				sdchild = NULL;
6593 			}
6594 		}
6595 	}
6596 
6597 	/* If asked for path_instance, return it. */
6598 	if (ppi)
6599 		*ppi = pi;
6600 
6601 	return (sdchild);
6602 }
6603 
6604 static void
6605 scsi_device_unconfig(dev_info_t *self, char *name, char *addr, int *circp)
6606 {
6607 	dev_info_t		*child = NULL;
6608 	mdi_pathinfo_t		*path = NULL;
6609 	char			*spathname;
6610 	int			rval;
6611 
6612 	ASSERT(self && addr && DEVI_BUSY_OWNED(self));
6613 
6614 	/*
6615 	 * We have a catch-22. We may have a demoted node that we need to find
6616 	 * and offline/remove. To find the node it it isn't demoted, we
6617 	 * use scsi_hba_find_child. If it's demoted, we then use
6618 	 * ndi_devi_findchild_by_callback.
6619 	 */
6620 	(void) scsi_hba_find_child(self, name, addr, 0, &child, &path, NULL);
6621 
6622 	if ((child == NULL) && (path == NULL)) {
6623 		child = ndi_devi_findchild_by_callback(self, name, addr,
6624 		    scsi_busctl_ua);
6625 		if (child) {
6626 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6627 			    "devinfo %s@%s found by callback",
6628 			    name ? name : "", addr));
6629 			ASSERT(ndi_flavor_get(child) ==
6630 			    SCSA_FLAVOR_SCSI_DEVICE);
6631 			if (ndi_flavor_get(child) != SCSA_FLAVOR_SCSI_DEVICE) {
6632 				SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6633 				    "devinfo %s@%s not SCSI_DEVICE flavored",
6634 				    name ? name : "", addr));
6635 				child = NULL;
6636 			}
6637 		}
6638 	}
6639 
6640 	if (child) {
6641 		ASSERT(child && (path == NULL));
6642 
6643 		/* Don't unconfig probe nodes. */
6644 		if (scsi_hba_devi_is_barrier(child)) {
6645 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6646 			    "devinfo %s@%s is_barrier, skip",
6647 			    name ? name : "", addr));
6648 			return;
6649 		}
6650 
6651 		/* Attempt to offline/remove the devinfo node */
6652 		if (ndi_devi_offline(child,
6653 		    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) == DDI_SUCCESS) {
6654 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6655 			    "devinfo %s@%s offlined and removed",
6656 			    name ? name : "", addr));
6657 		} else if (ndi_devi_device_remove(child)) {
6658 			/* Offline/remove failed, note new device_remove */
6659 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6660 			    "devinfo %s@%s offline failed, device_remove",
6661 			    name ? name : "", addr));
6662 		}
6663 	} else if (path) {
6664 		ASSERT(path && (child == NULL));
6665 
6666 		/*
6667 		 * Attempt to offline/remove the pathinfo node.
6668 		 *
6669 		 * NOTE: mdi_pi_offline of last path will fail if the
6670 		 * device is open (i.e. the client can't be offlined).
6671 		 *
6672 		 * NOTE: For mdi there is no REMOVE flag for mdi_pi_offline().
6673 		 * When mdi_pi_offline returns MDI_SUCCESS, we are responsible
6674 		 * for remove via mdi_pi_free().
6675 		 */
6676 		mdi_hold_path(path);
6677 		spathname = mdi_pi_spathname(path);	/* valid after free */
6678 		scsi_hba_devi_exit_phci(self, *circp);
6679 		rval = mdi_pi_offline(path, 0);
6680 		scsi_hba_devi_enter_phci(self, circp);
6681 		if (rval == MDI_SUCCESS) {
6682 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6683 			    "pathinfo %s offlined and removed", spathname));
6684 		} else if (mdi_pi_device_remove(path)) {
6685 			/* Offline/remove failed, note new device_remove */
6686 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6687 			    "pathinfo %s offline failed, "
6688 			    "device_remove", spathname));
6689 		}
6690 		mdi_rele_path(path);
6691 		if ((rval == MDI_SUCCESS) &&
6692 		    (mdi_pi_free(path, 0) != MDI_SUCCESS)) {	/* REMOVE */
6693 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6694 			    "pathinfo %s mdi_pi_free failed, "
6695 			    "device_remove", spathname));
6696 			(void) mdi_pi_device_remove(path);
6697 		}
6698 	} else {
6699 		ASSERT((path == NULL) && (child == NULL));
6700 
6701 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6702 		    "%s@%s not found", name ? name : "", addr));
6703 	}
6704 }
6705 
6706 /*
6707  * configure the device at the specified "@addr" address.
6708  */
6709 static struct scsi_device *
6710 scsi_hba_bus_configone_addr(dev_info_t *self, char *addr, scsi_enum_t se)
6711 {
6712 	int			circ;
6713 	struct scsi_device	*sd;
6714 
6715 	scsi_hba_devi_enter(self, &circ);
6716 	sd = scsi_device_config(self, NULL, addr, se, &circ, NULL);
6717 	scsi_hba_devi_exit(self, circ);
6718 	return (sd);
6719 }
6720 
6721 /*
6722  * unconfigure the device at the specified "@addr" address.
6723  */
6724 static void
6725 scsi_hba_bus_unconfigone_addr(dev_info_t *self, char *addr)
6726 {
6727 	int			circ;
6728 
6729 	scsi_hba_devi_enter(self, &circ);
6730 	(void) scsi_device_unconfig(self, NULL, addr, &circ);
6731 	scsi_hba_devi_exit(self, circ);
6732 }
6733 
6734 /*
6735  * The bus_config_all operations are multi-threaded for performance. A
6736  * separate thread per target and per LUN is used. The config handle is used
6737  * to coordinate all the threads at a given level and the config thread data
6738  * contains the required information for a specific thread to identify what it
6739  * is processing and the handle under which this is being processed.
6740  */
6741 
6742 /* multi-threaded config handle */
6743 struct	scsi_hba_mte_h {
6744 	dev_info_t		*h_self;	/* initiator port */
6745 	int			h_thr_count;
6746 	kmutex_t		h_lock;
6747 	kcondvar_t		h_cv;
6748 };
6749 
6750 /* target of 'self' config thread data */
6751 struct scsi_hba_mte_td {
6752 	struct scsi_hba_mte_h	*td_h;
6753 	char			*td_taddr;	/* target port */
6754 	int			td_mt;
6755 	scsi_enum_t		td_se;
6756 };
6757 
6758 /* Invoke callback on a vector of taddrs from multiple threads */
6759 static void
6760 scsi_hba_thread_taddrs(dev_info_t *self, char **taddrs, int mt,
6761     scsi_enum_t se, void (*callback)(void *arg))
6762 {
6763 	struct scsi_hba_mte_h	*h;	/* HBA header */
6764 	struct scsi_hba_mte_td	*td;	/* target data */
6765 	char			**taddr;
6766 
6767 	/* allocate and initialize the handle */
6768 	h = kmem_zalloc(sizeof (*h), KM_SLEEP);
6769 	mutex_init(&h->h_lock, NULL, MUTEX_DEFAULT, NULL);
6770 	cv_init(&h->h_cv, NULL, CV_DEFAULT, NULL);
6771 	h->h_self = self;
6772 
6773 	/* loop over all the targets */
6774 	for (taddr = taddrs; *taddr; taddr++) {
6775 		/* allocate a thread data structure for target */
6776 		td = kmem_alloc(sizeof (*td), KM_SLEEP);
6777 		td->td_h = h;
6778 		td->td_taddr = *taddr;
6779 		td->td_mt = mt;
6780 		td->td_se = se;
6781 
6782 		/* process the target */
6783 		mutex_enter(&h->h_lock);
6784 		h->h_thr_count++;
6785 		mutex_exit(&h->h_lock);
6786 
6787 		if (mt & SCSI_ENUMERATION_MT_TARGET_DISABLE)
6788 			callback((void *)td);
6789 		else
6790 			(void) thread_create(NULL, 0, callback, (void *)td,
6791 			    0, &p0, TS_RUN, minclsyspri);
6792 	}
6793 
6794 	/* wait for all the target threads to complete */
6795 	mutex_enter(&h->h_lock);
6796 	while (h->h_thr_count > 0)
6797 		cv_wait(&h->h_cv, &h->h_lock);
6798 	mutex_exit(&h->h_lock);
6799 
6800 	/* free the handle */
6801 	cv_destroy(&h->h_cv);
6802 	mutex_destroy(&h->h_lock);
6803 	kmem_free(h, sizeof (*h));
6804 }
6805 
6806 
6807 /* lun/secondary function of lun0 config thread data */
6808 struct scsi_hba_mte_ld {
6809 	struct scsi_hba_mte_h	*ld_h;
6810 	char			*ld_taddr;	/* target port */
6811 	scsi_lun64_t		ld_lun64;	/* lun */
6812 	int			ld_sfunc;	/* secondary function */
6813 	scsi_enum_t		ld_se;
6814 };
6815 
6816 /*
6817  * Enumerate the LUNs and secondary functions of the specified target. The
6818  * target portion of the "@addr" is already represented as a string in the
6819  * thread data, we add a ",lun" representation to this and perform a
6820  * bus_configone byte of enumeration on that "@addr".
6821  */
6822 static void
6823 scsi_hba_enum_lsf_of_tgt_thr(void *arg)
6824 {
6825 	struct scsi_hba_mte_ld	*ld = (struct scsi_hba_mte_ld *)arg;
6826 	struct scsi_hba_mte_h	*h = ld->ld_h;
6827 	dev_info_t		*self = h->h_self;
6828 	char			addr[SCSI_MAXNAMELEN];
6829 
6830 	/* make string form of "@taddr,lun[,sfunc]" and see if it exists */
6831 	if (ld->ld_sfunc == -1)
6832 		(void) snprintf(addr, sizeof (addr),
6833 		    "%s,%" PRIx64, ld->ld_taddr, ld->ld_lun64);
6834 	else
6835 		(void) snprintf(addr, sizeof (addr),
6836 		    "%s,%" PRIx64 ",%x",
6837 		    ld->ld_taddr, ld->ld_lun64, ld->ld_sfunc);
6838 
6839 	/* configure device at that unit-address address */
6840 	(void) scsi_hba_bus_configone_addr(self, addr, ld->ld_se);
6841 
6842 	/* signal completion of this LUN thread to the target */
6843 	mutex_enter(&h->h_lock);
6844 	if (--h->h_thr_count == 0)
6845 		cv_broadcast(&h->h_cv);
6846 	mutex_exit(&h->h_lock);
6847 
6848 	/* free config thread data */
6849 	kmem_free(ld, sizeof (*ld));
6850 }
6851 
6852 /* Format of SCSI REPORT_LUNS report */
6853 typedef struct scsi_lunrpt {
6854 	uchar_t		lunrpt_len_msb;		/* # LUNs being reported */
6855 	uchar_t		lunrpt_len_mmsb;
6856 	uchar_t		lunrpt_len_mlsb;
6857 	uchar_t		lunrpt_len_lsb;
6858 	uchar_t		lunrpt_reserved[4];
6859 	scsi_lun_t	lunrpt_luns[1];		/* LUNs, variable size */
6860 } scsi_lunrpt_t;
6861 
6862 /*
6863  * scsi_device_reportluns()
6864  *
6865  * Callers of this routine should ensure that the 'sd0' scsi_device structure
6866  * and 'pi' path_instance specified are associated with a responding LUN0.
6867  * This should not be called for SCSI-1 devices.
6868  *
6869  * To get a LUN report, we must allocate a buffer. To know how big to make the
6870  * buffer, we must know the number of LUNs. To know the number of LUNs, we must
6871  * get a LUN report. We first issue a SCMD_REPORT_LUNS command using a
6872  * reasonably sized buffer that's big enough to report all LUNs for most
6873  * typical devices. If it turns out that we needed a bigger buffer, we attempt
6874  * to allocate a buffer of sufficient size, and reissue the command. If the
6875  * first command succeeds, but the second fails, we return whatever we were
6876  * able to get the first time. We return enough information for the caller to
6877  * tell whether he got all the LUNs or only a subset.
6878  *
6879  * If successful, we allocate an array of scsi_lun_t to hold the results. The
6880  * caller must kmem_free(*lunarrayp, *sizep) when finished with it. Upon
6881  * successful return return value is NDI_SUCCESS and:
6882  *
6883  *	*lunarrayp points to the allocated array,
6884  *	*nlunsp is the number of valid LUN entries in the array,
6885  *	*tlunsp is the total number of LUNs in the target,
6886  *	*sizep is the size of the lunarrayp array, which must be freed.
6887  *
6888  * If the *nlunsp is less than *tlunsp, then we were only able to retrieve a
6889  * subset of the total set of LUNs in the target.
6890  */
6891 static int
6892 scsi_device_reportluns(struct scsi_device *sd0, char *taddr, int pi,
6893     scsi_lun_t **lunarrayp, uint32_t *nlunsp, uint32_t *tlunsp, size_t *sizep)
6894 {
6895 	struct buf	*lunrpt_bp;
6896 	struct scsi_pkt *lunrpt_pkt;
6897 	scsi_lunrpt_t	*lunrpt;
6898 	uint32_t	bsize;
6899 	uint32_t	tluns, nluns;
6900 	int		default_maxluns = scsi_lunrpt_default_max;
6901 	dev_info_t	*child;
6902 
6903 	ASSERT(sd0 && lunarrayp && nlunsp && tlunsp && sizep);
6904 
6905 	/*
6906 	 * NOTE: child should only be used in SCSI_HBA_LOG context since with
6907 	 * vHCI enumeration it may be the vHCI 'client' devinfo child instead
6908 	 * of a child of the 'self' pHCI we are enumerating.
6909 	 */
6910 	child = sd0->sd_dev;
6911 
6912 	/* first try, look for up to scsi_lunrpt_default_max LUNs */
6913 	nluns = default_maxluns;
6914 
6915 again:	bsize = sizeof (struct scsi_lunrpt) +
6916 	    ((nluns - 1) * sizeof (struct scsi_lun));
6917 
6918 	lunrpt_bp = scsi_alloc_consistent_buf(&sd0->sd_address,
6919 	    (struct buf *)NULL, bsize, B_READ, SLEEP_FUNC, NULL);
6920 	if (lunrpt_bp == NULL) {
6921 		SCSI_HBA_LOG((_LOG(1), NULL, child, "failed alloc"));
6922 		return (NDI_NOMEM);
6923 	}
6924 
6925 	lunrpt_pkt = scsi_init_pkt(&sd0->sd_address,
6926 	    (struct scsi_pkt *)NULL, lunrpt_bp, CDB_GROUP5,
6927 	    sizeof (struct scsi_arq_status), 0, PKT_CONSISTENT,
6928 	    SLEEP_FUNC, NULL);
6929 	if (lunrpt_pkt == NULL) {
6930 		SCSI_HBA_LOG((_LOG(1), NULL, child, "failed init"));
6931 		scsi_free_consistent_buf(lunrpt_bp);
6932 		return (NDI_NOMEM);
6933 	}
6934 
6935 	(void) scsi_setup_cdb((union scsi_cdb *)lunrpt_pkt->pkt_cdbp,
6936 	    SCMD_REPORT_LUNS, 0, bsize, 0);
6937 
6938 	lunrpt_pkt->pkt_time = scsi_lunrpt_timeout;
6939 
6940 	/*
6941 	 * When sd0 is a vHCI scsi device, we need reportlun to be issued
6942 	 * against a specific LUN0 path_instance that we are enumerating.
6943 	 */
6944 	lunrpt_pkt->pkt_path_instance = pi;
6945 	lunrpt_pkt->pkt_flags |= FLAG_PKT_PATH_INSTANCE;
6946 
6947 	/*
6948 	 * NOTE: scsi_poll may not allow HBA specific recovery from TRAN_BUSY.
6949 	 */
6950 	if (scsi_poll(lunrpt_pkt) < 0) {
6951 		SCSI_HBA_LOG((_LOG(2), NULL, child, "reportlun not supported"));
6952 		scsi_destroy_pkt(lunrpt_pkt);
6953 		scsi_free_consistent_buf(lunrpt_bp);
6954 		return (NDI_FAILURE);
6955 	}
6956 
6957 	scsi_destroy_pkt(lunrpt_pkt);
6958 
6959 	lunrpt = (scsi_lunrpt_t *)lunrpt_bp->b_un.b_addr;
6960 
6961 	/* Compute the total number of LUNs in the target */
6962 	tluns = (((uint_t)lunrpt->lunrpt_len_msb << 24) |
6963 	    ((uint_t)lunrpt->lunrpt_len_mmsb << 16) |
6964 	    ((uint_t)lunrpt->lunrpt_len_mlsb << 8) |
6965 	    ((uint_t)lunrpt->lunrpt_len_lsb)) >> 3;
6966 
6967 	if (tluns == 0) {
6968 		/* Illegal response -- this target is broken */
6969 		SCSI_HBA_LOG((_LOG(1), NULL, child, "illegal tluns of zero"));
6970 		scsi_free_consistent_buf(lunrpt_bp);
6971 		return (DDI_NOT_WELL_FORMED);
6972 	}
6973 
6974 	if (tluns > nluns) {
6975 		/* have more than we allocated space for */
6976 		if (nluns == default_maxluns) {
6977 			/* first time around, reallocate larger */
6978 			scsi_free_consistent_buf(lunrpt_bp);
6979 			nluns = tluns;
6980 			goto again;
6981 		}
6982 
6983 		/* uh oh, we got a different tluns the second time! */
6984 		SCSI_HBA_LOG((_LOG(1), NULL, child,
6985 		    "tluns changed from %d to %d", nluns, tluns));
6986 	} else
6987 		nluns = tluns;
6988 
6989 	/*
6990 	 * Now we have:
6991 	 *	lunrpt_bp is the buffer we're using;
6992 	 *	tluns is the total number of LUNs the target says it has;
6993 	 *	nluns is the number of LUNs we were able to get into the buffer.
6994 	 *
6995 	 * Copy the data out of scarce iopb memory into regular kmem.
6996 	 * The caller must kmem_free(*lunarrayp, *sizep) when finished with it.
6997 	 */
6998 	*lunarrayp = (scsi_lun_t *)kmem_alloc(
6999 	    nluns * sizeof (scsi_lun_t), KM_SLEEP);
7000 	if (*lunarrayp == NULL) {
7001 		SCSI_HBA_LOG((_LOG(1), NULL, child, "NULL lunarray"));
7002 		scsi_free_consistent_buf(lunrpt_bp);
7003 		return (NDI_NOMEM);
7004 	}
7005 
7006 	*sizep = nluns * sizeof (scsi_lun_t);
7007 	*nlunsp = nluns;
7008 	*tlunsp = tluns;
7009 	bcopy((void *)&lunrpt->lunrpt_luns, (void *)*lunarrayp, *sizep);
7010 	scsi_free_consistent_buf(lunrpt_bp);
7011 	SCSI_HBA_LOG((_LOG(3), NULL, child,
7012 	    "@%s,0 path %d: %d/%d luns", taddr, pi, nluns, tluns));
7013 	return (NDI_SUCCESS);
7014 }
7015 
7016 /*
7017  * Enumerate all the LUNs and secondary functions of the specified 'taddr'
7018  * target port as accessed via 'self' pHCI.  Note that sd0 may be associated
7019  * with a child of the vHCI instead of 'self' - in this case the 'pi'
7020  * path_instance is used to ensure that the SCMD_REPORT_LUNS command is issued
7021  * through the 'self' pHCI path.
7022  *
7023  * We multi-thread across all the LUNs and secondary functions and enumerate
7024  * them. Which LUNs exist is based on SCMD_REPORT_LUNS data.
7025  *
7026  * The scsi_device we are called with should be for LUN0 and has been probed.
7027  *
7028  * This function is structured so that an HBA that has a different target
7029  * addressing structure can still use this function to enumerate the its
7030  * LUNs if it uses "taddr,lun" for its LUN space.
7031  *
7032  * We make assumptions about other LUNs associated with the target:
7033  *
7034  *	For SCSI-2 and SCSI-3 target we will issue the SCSI report_luns
7035  *	command. If this fails or we have a SCSI-1 then the number of
7036  *	LUNs is determined based on SCSI_OPTIONS_NLUNS. For a SCSI-1
7037  *	target we never probe above LUN 8, even if SCSI_OPTIONS_NLUNS
7038  *	indicates we should.
7039  *
7040  * HBA drivers wanting a different set of assumptions should implement their
7041  * own LUN enumeration code.
7042  */
7043 static int
7044 scsi_hba_enum_lsf_of_t(struct scsi_device *sd0,
7045     dev_info_t *self, char *taddr, int pi, int mt, scsi_enum_t se)
7046 {
7047 	dev_info_t		*child;
7048 	scsi_hba_tran_t		*tran;
7049 	impl_scsi_tgtmap_t	*tgtmap;
7050 	damap_id_t		tgtid;
7051 	damap_t			*tgtdam;
7052 	damap_t			*lundam = NULL;
7053 	struct scsi_hba_mte_h	*h;
7054 	struct scsi_hba_mte_ld	*ld;
7055 	int			aver;
7056 	scsi_lun_t		*lunp = NULL;
7057 	int			lun;
7058 	uint32_t		nluns;
7059 	uint32_t		tluns;
7060 	size_t			size;
7061 	scsi_lun64_t		lun64;
7062 	int			maxluns;
7063 
7064 	/*
7065 	 * If LUN0 failed then we have no other LUNs.
7066 	 *
7067 	 * NOTE: We need sd_inq to be valid to check ansi version. Since
7068 	 * scsi_unprobe is now a noop (sd_inq freeded in
7069 	 * scsi_busctl_uninitchild) sd_inq remains valid even if a target
7070 	 * driver detach(9E) occurs, resulting in a scsi_unprobe call
7071 	 * (sd_uninit_prevent keeps sd_inq valid by failing any
7072 	 * device_uninitchild attempts).
7073 	 */
7074 	ASSERT(sd0 && sd0->sd_uninit_prevent && sd0->sd_dev && sd0->sd_inq);
7075 	if ((sd0 == NULL) || (sd0->sd_dev == NULL) || (sd0->sd_inq == NULL)) {
7076 		SCSI_HBA_LOG((_LOG(1), NULL, sd0 ? sd0->sd_dev : NULL,
7077 		    "not setup correctly:%s%s%s",
7078 		    (sd0 == NULL) ? " device" : "",
7079 		    (sd0 && (sd0->sd_dev == NULL)) ? " dip" : "",
7080 		    (sd0 && (sd0->sd_inq == NULL)) ? " inq" : ""));
7081 		return (DDI_FAILURE);
7082 	}
7083 
7084 	/*
7085 	 * NOTE: child should only be used in SCSI_HBA_LOG context since with
7086 	 * vHCI enumeration it may be the vHCI 'client' devinfo child instead
7087 	 * of a child of the 'self' pHCI we are enumerating.
7088 	 */
7089 	child = sd0->sd_dev;
7090 
7091 	/* Determine if we are reporting lun observations into lunmap. */
7092 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
7093 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
7094 	if (tgtmap) {
7095 		tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
7096 		tgtid = damap_lookup(tgtdam, taddr);
7097 		if (tgtid != NODAM) {
7098 			lundam = damap_id_priv_get(tgtdam, tgtid);
7099 			damap_id_rele(tgtdam, tgtid);
7100 			ASSERT(lundam);
7101 		}
7102 	}
7103 
7104 	if (lundam) {
7105 		/* If using lunmap, start the observation */
7106 		scsi_lunmap_set_begin(self, lundam);
7107 	} else {
7108 		/* allocate and initialize the LUN handle */
7109 		h = kmem_zalloc(sizeof (*h), KM_SLEEP);
7110 		mutex_init(&h->h_lock, NULL, MUTEX_DEFAULT, NULL);
7111 		cv_init(&h->h_cv, NULL, CV_DEFAULT, NULL);
7112 		h->h_self = self;
7113 	}
7114 
7115 	/* See if SCMD_REPORT_LUNS works for SCSI-2 and beyond */
7116 	aver = sd0->sd_inq->inq_ansi;
7117 	if ((aver >= SCSI_VERSION_2) && (scsi_device_reportluns(sd0,
7118 	    taddr, pi, &lunp, &nluns, &tluns, &size) == NDI_SUCCESS)) {
7119 
7120 		ASSERT(lunp && (size > 0) && (nluns > 0) && (tluns > 0));
7121 
7122 		/* loop over the reported LUNs */
7123 		SCSI_HBA_LOG((_LOG(2), NULL, child,
7124 		    "@%s,0 path %d: enumerating %d reported lun%s", taddr, pi,
7125 		    nluns, nluns > 1 ? "s" : ""));
7126 
7127 		for (lun = 0; lun < nluns; lun++) {
7128 			lun64 = scsi_lun_to_lun64(lunp[lun]);
7129 
7130 			if (lundam) {
7131 				if (scsi_lunmap_set_add(self, lundam,
7132 				    taddr, lun64, -1) != DDI_SUCCESS) {
7133 					SCSI_HBA_LOG((_LOG_NF(WARN),
7134 					    "@%s,%" PRIx64 " failed to create",
7135 					    taddr, lun64));
7136 				}
7137 			} else {
7138 				if (lun64 == 0)
7139 					continue;
7140 
7141 				/* allocate a thread data structure for LUN */
7142 				ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7143 				ld->ld_h = h;
7144 				ld->ld_taddr = taddr;
7145 				ld->ld_lun64 = lun64;
7146 				ld->ld_sfunc = -1;
7147 				ld->ld_se = se;
7148 
7149 				/* process the LUN */
7150 				mutex_enter(&h->h_lock);
7151 				h->h_thr_count++;
7152 				mutex_exit(&h->h_lock);
7153 
7154 				if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7155 					scsi_hba_enum_lsf_of_tgt_thr(
7156 					    (void *)ld);
7157 				else
7158 					(void) thread_create(NULL, 0,
7159 					    scsi_hba_enum_lsf_of_tgt_thr,
7160 					    (void *)ld, 0, &p0, TS_RUN,
7161 					    minclsyspri);
7162 			}
7163 		}
7164 
7165 		/* free the LUN array allocated by scsi_device_reportluns */
7166 		kmem_free(lunp, size);
7167 	} else {
7168 		/* Couldn't get SCMD_REPORT_LUNS data */
7169 		if (aver >= SCSI_VERSION_3) {
7170 			if (se == SE_HP)
7171 				SCSI_HBA_LOG((_LOG(WARN), NULL, child,
7172 				    "enumeration failed during report_lun"));
7173 			else
7174 				SCSI_HBA_LOG((_LOG(2), NULL, child,
7175 				    "enumeration failed during report_lun"));
7176 		}
7177 
7178 		/* Determine the number of LUNs to enumerate. */
7179 		maxluns = scsi_get_scsi_maxluns(sd0);
7180 
7181 		/* loop over possible LUNs, skipping LUN0 */
7182 		if (maxluns > 1)
7183 			SCSI_HBA_LOG((_LOG(2), NULL, child,
7184 			    "@%s,0 path %d: enumerating luns 1-%d", taddr, pi,
7185 			    maxluns - 1));
7186 		else
7187 			SCSI_HBA_LOG((_LOG(2), NULL, child,
7188 			    "@%s,0 path %d: enumerating just lun0", taddr, pi));
7189 
7190 		for (lun64 = 0; lun64 < maxluns; lun64++) {
7191 			if (lundam) {
7192 				if (scsi_lunmap_set_add(self, lundam,
7193 				    taddr, lun64, -1) != DDI_SUCCESS) {
7194 					SCSI_HBA_LOG((_LOG_NF(WARN),
7195 					    "@%s,%" PRIx64 " failed to create",
7196 					    taddr, lun64));
7197 				}
7198 			} else {
7199 				if (lun64 == 0)
7200 					continue;
7201 
7202 				/* allocate a thread data structure for LUN */
7203 				ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7204 				ld->ld_h = h;
7205 				ld->ld_taddr = taddr;
7206 				ld->ld_lun64 = lun64;
7207 				ld->ld_sfunc = -1;
7208 				ld->ld_se = se;
7209 
7210 				/* process the LUN */
7211 				mutex_enter(&h->h_lock);
7212 				h->h_thr_count++;
7213 				mutex_exit(&h->h_lock);
7214 				if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7215 					scsi_hba_enum_lsf_of_tgt_thr(
7216 					    (void *)ld);
7217 				else
7218 					(void) thread_create(NULL, 0,
7219 					    scsi_hba_enum_lsf_of_tgt_thr,
7220 					    (void *)ld, 0, &p0, TS_RUN,
7221 					    minclsyspri);
7222 			}
7223 		}
7224 	}
7225 
7226 	/*
7227 	 * If we have an embedded service as a secondary function on LUN0 and
7228 	 * the primary LUN0 function is different than the secondary function
7229 	 * then enumerate the secondary function. The sfunc value is the dtype
7230 	 * associated with the embedded service.
7231 	 *
7232 	 * inq_encserv: enclosure service and our dtype is not DTYPE_ESI
7233 	 * or DTYPE_UNKNOWN then create a separate DTYPE_ESI node for
7234 	 * enclosure service access.
7235 	 */
7236 	ASSERT(sd0->sd_inq);
7237 	if (sd0->sd_inq->inq_encserv &&
7238 	    ((sd0->sd_inq->inq_dtype & DTYPE_MASK) != DTYPE_UNKNOWN) &&
7239 	    ((sd0->sd_inq->inq_dtype & DTYPE_MASK) != DTYPE_ESI) &&
7240 	    ((sd0->sd_inq->inq_ansi >= SCSI_VERSION_3))) {
7241 		if (lundam) {
7242 			if (scsi_lunmap_set_add(self, lundam,
7243 			    taddr, 0, DTYPE_ESI) != DDI_SUCCESS) {
7244 				SCSI_HBA_LOG((_LOG_NF(WARN),
7245 				    "@%s,0,%x failed to create",
7246 				    taddr, DTYPE_ESI));
7247 			}
7248 		} else {
7249 			/* allocate a thread data structure for sfunc */
7250 			ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7251 			ld->ld_h = h;
7252 			ld->ld_taddr = taddr;
7253 			ld->ld_lun64 = 0;
7254 			ld->ld_sfunc = DTYPE_ESI;
7255 			ld->ld_se = se;
7256 
7257 			/* process the LUN */
7258 			mutex_enter(&h->h_lock);
7259 			h->h_thr_count++;
7260 			mutex_exit(&h->h_lock);
7261 			if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7262 				scsi_hba_enum_lsf_of_tgt_thr((void *)ld);
7263 			else
7264 				(void) thread_create(NULL, 0,
7265 				    scsi_hba_enum_lsf_of_tgt_thr, (void *)ld,
7266 				    0, &p0, TS_RUN, minclsyspri);
7267 		}
7268 	}
7269 
7270 	/*
7271 	 * Future: Add secondary function support for:
7272 	 *	inq_mchngr (DTYPE_CHANGER)
7273 	 *	inq_sccs (DTYPE_ARRAY_CTRL)
7274 	 */
7275 
7276 	if (lundam) {
7277 		/* If using lunmap, end the observation */
7278 		scsi_lunmap_set_end(self, lundam);
7279 	} else {
7280 		/* wait for all the LUN threads of this target to complete */
7281 		mutex_enter(&h->h_lock);
7282 		while (h->h_thr_count > 0)
7283 			cv_wait(&h->h_cv, &h->h_lock);
7284 		mutex_exit(&h->h_lock);
7285 
7286 		/* free the target handle */
7287 		cv_destroy(&h->h_cv);
7288 		mutex_destroy(&h->h_lock);
7289 		kmem_free(h, sizeof (*h));
7290 	}
7291 
7292 	return (DDI_SUCCESS);
7293 }
7294 
7295 /*
7296  * Enumerate LUN0 and all other LUNs and secondary functions associated with
7297  * the specified target address.
7298  *
7299  * Return NDI_SUCCESS if we might have created a new node.
7300  * Return NDI_FAILURE if we definitely did not create a new node.
7301  */
7302 static int
7303 scsi_hba_bus_config_taddr(dev_info_t *self, char *taddr, int mt, scsi_enum_t se)
7304 {
7305 	char			addr[SCSI_MAXNAMELEN];
7306 	struct scsi_device	*sd;
7307 	int			circ;
7308 	int			ret;
7309 	int			pi;
7310 
7311 	/* See if LUN0 of the specified target exists. */
7312 	(void) snprintf(addr, sizeof (addr), "%s,0", taddr);
7313 
7314 	scsi_hba_devi_enter(self, &circ);
7315 	sd = scsi_device_config(self, NULL, addr, se, &circ, &pi);
7316 
7317 	if (sd) {
7318 		/*
7319 		 * LUN0 exists, enumerate all the other LUNs.
7320 		 *
7321 		 * With vHCI enumeration, when 'self' is a pHCI the sd
7322 		 * scsi_device may be associated with the vHCI 'client'.
7323 		 * In this case 'pi' is the path_instance needed to
7324 		 * continue enumeration communication LUN0 via 'self'
7325 		 * pHCI and specific 'taddr' target address.
7326 		 *
7327 		 * We prevent the removal of LUN0 until we are done with
7328 		 * prevent/allow because we must exit the parent for
7329 		 * multi-threaded scsi_hba_enum_lsf_of_t().
7330 		 *
7331 		 * NOTE: scsi_unprobe is a noop, sd->sd_inq is valid until
7332 		 * device_uninitchild - so sd_uninit_prevent keeps sd_inq valid
7333 		 * by failing any device_uninitchild attempts.
7334 		 */
7335 		ret = NDI_SUCCESS;
7336 		sd->sd_uninit_prevent++;
7337 		scsi_hba_devi_exit(self, circ);
7338 
7339 		(void) scsi_hba_enum_lsf_of_t(sd, self, taddr, pi, mt, se);
7340 
7341 		scsi_hba_devi_enter(self, &circ);
7342 		sd->sd_uninit_prevent--;
7343 	} else
7344 		ret = NDI_FAILURE;
7345 	scsi_hba_devi_exit(self, circ);
7346 	return (ret);
7347 }
7348 
7349 /* Config callout from scsi_hba_thread_taddrs */
7350 static void
7351 scsi_hba_taddr_config_thr(void *arg)
7352 {
7353 	struct scsi_hba_mte_td	*td = (struct scsi_hba_mte_td *)arg;
7354 	struct scsi_hba_mte_h	*h = td->td_h;
7355 
7356 	(void) scsi_hba_bus_config_taddr(h->h_self, td->td_taddr,
7357 	    td->td_mt, td->td_se);
7358 
7359 	/* signal completion of this target thread to the HBA */
7360 	mutex_enter(&h->h_lock);
7361 	if (--h->h_thr_count == 0)
7362 		cv_broadcast(&h->h_cv);
7363 	mutex_exit(&h->h_lock);
7364 
7365 	/* free config thread data */
7366 	kmem_free(td, sizeof (*td));
7367 }
7368 
7369 /*
7370  * Enumerate all the children of the specified SCSI parallel interface (spi).
7371  * An HBA associated with a non-parallel scsi bus should be using another bus
7372  * level enumeration implementation (possibly their own) and calling
7373  * scsi_hba_bus_config_taddr to do enumeration of devices associated with a
7374  * particular target address.
7375  *
7376  * On an spi bus the targets are sequentially enumerated based on the
7377  * width of the bus. We also take care to try to skip the HBAs own initiator
7378  * id. See scsi_hba_enum_lsf_of_t() for LUN and secondary function enumeration.
7379  *
7380  * Return NDI_SUCCESS if we might have created a new node.
7381  * Return NDI_FAILURE if we definitely did not create a new node.
7382  *
7383  * Note: At some point we may want to expose this interface in transport.h
7384  * if we find an hba that implements bus_config but still uses spi-like target
7385  * addresses.
7386  */
7387 static int
7388 scsi_hba_bus_configall_spi(dev_info_t *self, int mt)
7389 {
7390 	int	options;
7391 	int	ntargets;
7392 	int	id;
7393 	int	tgt;
7394 	char	**taddrs;
7395 	char	**taddr;
7396 	char	*tbuf;
7397 
7398 	/*
7399 	 * Find the number of targets supported on the bus. Look at the per
7400 	 * bus scsi-options property on the HBA node and check its
7401 	 * SCSI_OPTIONS_WIDE setting.
7402 	 */
7403 	options = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7404 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-options", -1);
7405 	if ((options != -1) && ((options & SCSI_OPTIONS_WIDE) == 0))
7406 		ntargets = NTARGETS;			/* 8 */
7407 	else
7408 		ntargets = NTARGETS_WIDE;		/* 16 */
7409 
7410 	/*
7411 	 * Find the initiator-id for the HBA so we can skip that. We get the
7412 	 * cached value on the HBA node, established in scsi_hba_attach_setup.
7413 	 * If we were unable to determine the id then we rely on the HBA to
7414 	 * fail gracefully when asked to enumerate itself.
7415 	 */
7416 	id = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7417 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-initiator-id", -1);
7418 	if (id > ntargets) {
7419 		SCSI_HBA_LOG((_LOG(1), self, NULL,
7420 		    "'scsi-initiator-id' bogus for %d target bus: %d",
7421 		    ntargets, id));
7422 		id = -1;
7423 	}
7424 	SCSI_HBA_LOG((_LOG(2), self, NULL,
7425 	    "enumerating targets 0-%d skip %d", ntargets, id));
7426 
7427 	/* form vector of target addresses */
7428 	taddrs = kmem_zalloc(sizeof (char *) * (ntargets + 1), KM_SLEEP);
7429 	for (tgt = 0, taddr = taddrs; tgt < ntargets; tgt++) {
7430 		/* skip initiator */
7431 		if (tgt == id)
7432 			continue;
7433 
7434 		/* convert to string and enumerate the target address */
7435 		tbuf = kmem_alloc(((tgt/16) + 1) + 1, KM_SLEEP);
7436 		(void) sprintf(tbuf, "%x", tgt);
7437 		ASSERT(strlen(tbuf) == ((tgt/16) + 1));
7438 		*taddr++ = tbuf;
7439 	}
7440 
7441 	/* null terminate vector of target addresses */
7442 	*taddr = NULL;
7443 
7444 	/* configure vector of target addresses */
7445 	scsi_hba_thread_taddrs(self, taddrs, mt, SE_BUSCONFIG,
7446 	    scsi_hba_taddr_config_thr);
7447 
7448 	/* free vector of target addresses */
7449 	for (taddr = taddrs; *taddr; taddr++)
7450 		kmem_free(*taddr, strlen(*taddr) + 1);
7451 	kmem_free(taddrs, sizeof (char *) * (ntargets + 1));
7452 	return (NDI_SUCCESS);
7453 }
7454 
7455 /*
7456  * Transport independent bus_configone BUS_CONFIG_ONE implementation.  Takes
7457  * same arguments, minus op, as scsi_hba_bus_config(), tran_bus_config(),
7458  * and scsi_hba_bus_config_spi().
7459  */
7460 int
7461 scsi_hba_bus_configone(dev_info_t *self, uint_t flags, char *arg,
7462     dev_info_t **childp)
7463 {
7464 	int			ret;
7465 	int			circ;
7466 	char			*name, *addr;
7467 	char			*lcp;
7468 	char			sc1, sc2;
7469 	char			nameaddr[SCSI_MAXNAMELEN];
7470 	extern int		i_ndi_make_spec_children(dev_info_t *, uint_t);
7471 	struct scsi_device	*sd0, *sd;
7472 	scsi_lun64_t		lun64;
7473 	int			mt;
7474 
7475 	/* parse_name modifies arg1, we must duplicate "name@addr" */
7476 	(void) strcpy(nameaddr, arg);
7477 	i_ddi_parse_name(nameaddr, &name, &addr, NULL);
7478 
7479 	/* verify the form of the node - we need an @addr */
7480 	if ((name == NULL) || (addr == NULL) ||
7481 	    (*name == '\0') || (*addr == '\0')) {
7482 		/*
7483 		 * OBP may create ill formed template/stub/wild-card
7484 		 * nodes (no @addr) for legacy driver loading methods -
7485 		 * ignore them.
7486 		 */
7487 		SCSI_HBA_LOG((_LOG(2), self, NULL, "%s ill formed", arg));
7488 		return (NDI_FAILURE);
7489 	}
7490 
7491 	/*
7492 	 * Check to see if this is a non-scsi flavor configuration operation.
7493 	 */
7494 	if (strcmp(name, "smp") == 0) {
7495 		/*
7496 		 * Configure the child, and if we're successful return with
7497 		 * active hold.
7498 		 */
7499 		return (smp_hba_bus_config(self, addr, childp));
7500 	}
7501 
7502 	/*
7503 	 * The framework does not ensure the creation of driver.conf
7504 	 * nodes prior to calling a nexus bus_config. For legacy
7505 	 * support of driver.conf file nodes we want to create our
7506 	 * driver.conf file children now so that we can detect if we
7507 	 * are being asked to bus_configone one of these nodes.
7508 	 *
7509 	 * Needing driver.conf file nodes prior to bus config is unique
7510 	 * to scsi_enumeration mixed mode (legacy driver.conf and
7511 	 * dynamic SID node) support. There is no general need for the
7512 	 * framework to make driver.conf children prior to bus_config.
7513 	 *
7514 	 * We enter our HBA (self) prior to scsi_device_config, and
7515 	 * pass it our circ. The scsi_device_config may exit the
7516 	 * HBA around scsi_probe() operations to allow for parallelism.
7517 	 * This is done after the probe node "@addr" is available as a
7518 	 * barrier to prevent parallel probes of the same device. The
7519 	 * probe node is also configured in a way that it can't be
7520 	 * removed by the framework until we are done with it.
7521 	 *
7522 	 * NOTE: The framework is currently preventing many parallel
7523 	 * sibling operations (such as attaches), so the parallelism
7524 	 * we are providing is of marginal use until that is improved.
7525 	 * The most logical way to solve this would be to have separate
7526 	 * target and lun nodes. This would be a large change in the
7527 	 * format of /devices paths and is not being pursued at this
7528 	 * time. The need for parallelism will become more of an issue
7529 	 * with top-down attach for mpxio/vhci and for iSCSI support.
7530 	 * We may want to eventually want a dual mode implementation,
7531 	 * where the HBA determines if we should construct separate
7532 	 * target and lun devinfo nodes.
7533 	 */
7534 	scsi_hba_devi_enter(self, &circ);
7535 	SCSI_HBA_LOG((_LOG(4), self, NULL, "%s@%s config_one", name, addr));
7536 	(void) i_ndi_make_spec_children(self, flags);
7537 
7538 	/*
7539 	 * For bus_configone, we make sure that we can find LUN0
7540 	 * first. This allows the delayed probe/barrier deletion for a
7541 	 * non-existent LUN0 (if enabled in scsi_device_config) to
7542 	 * cover all LUNs on the target. This is done to minimize the
7543 	 * number of independent target selection timeouts that occur
7544 	 * when a target with many LUNs is no longer accessible
7545 	 * (powered off). This removes the need for target driver
7546 	 * probe cache implementations.
7547 	 *
7548 	 * This optimization may not be desirable in a pure bridge
7549 	 * environment where targets on the other side of the bridge
7550 	 * show up as LUNs to the host. If we ever need to support
7551 	 * such a configuration then we should consider implementing a
7552 	 * SCSI_OPTIONS_ILUN0 bit.
7553 	 *
7554 	 * NOTE: we are *not* applying any target limitation filtering
7555 	 * to bus_configone, which means that we are relying on the
7556 	 * HBA tran_tgt_init entry point invoked by scsi_busctl_initchild
7557 	 * to fail.
7558 	 */
7559 	sd0 = (struct scsi_device *)-1;
7560 	lcp = strchr(addr, ',');		/* "addr,lun[,sfunc]" */
7561 	if (lcp) {
7562 		/*
7563 		 * With "tgt,lun[,sfunc]" addressing, multiple addressing levels
7564 		 * have been compressed into single devinfo node unit-address.
7565 		 * This presents a mismatch - there is no bus_config to discover
7566 		 * LUNs below a specific target, the only choice is to
7567 		 * BUS_CONFIG_ALL the HBA. To support BUS_CONFIG_ALL_LUNS below
7568 		 * a specific target, a bus_configone with lun address of "*"
7569 		 * triggers lun discovery below a target.
7570 		 */
7571 		if (*(lcp + 1) == '*') {
7572 			mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7573 			    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7574 			    "scsi-enumeration", scsi_enumeration);
7575 			mt |= scsi_hba_log_mt_disable;
7576 
7577 			SCSI_HBA_LOG((_LOG(2), self, NULL,
7578 			    "%s@%s lun enumeration triggered", name, addr));
7579 			*lcp = '\0';		/* turn ',' into '\0' */
7580 			scsi_hba_devi_exit(self, circ);
7581 			(void) scsi_hba_bus_config_taddr(self, addr,
7582 			    mt, SE_BUSCONFIG);
7583 			return (NDI_FAILURE);
7584 		}
7585 
7586 		/* convert hex lun number from ascii */
7587 		lun64 = scsi_addr_to_lun64(lcp + 1);
7588 
7589 		if ((lun64 != 0) && (lun64 != SCSI_LUN64_ILLEGAL)) {
7590 			/*
7591 			 * configure ",0" lun first, saving off
7592 			 * original lun characters.
7593 			 */
7594 			sc1 = *(lcp + 1);
7595 			sc2 = *(lcp + 2);
7596 			*(lcp + 1) = '0';
7597 			*(lcp + 2) = '\0';
7598 			sd0 = scsi_device_config(self,
7599 			    NULL, addr, SE_BUSCONFIG, &circ, NULL);
7600 
7601 			/* restore original lun */
7602 			*(lcp + 1) = sc1;
7603 			*(lcp + 2) = sc2;
7604 
7605 			/*
7606 			 * Apply maxlun filtering.
7607 			 *
7608 			 * Future: We still have the kludged
7609 			 * scsi_check_ss2_LUN_limit() filtering off
7610 			 * scsi_probe() to catch bogus driver.conf
7611 			 * entries.
7612 			 */
7613 			if (sd0 && (lun64 < SCSI_32LUNS_PER_TARGET) &&
7614 			    (lun64 >= scsi_get_scsi_maxluns(sd0))) {
7615 				sd0 = NULL;
7616 				SCSI_HBA_LOG((_LOG(4), self, NULL,
7617 				    "%s@%s filtered", name, addr));
7618 			} else
7619 				SCSI_HBA_LOG((_LOG(4), self, NULL,
7620 				    "%s@%s lun 0 %s", name, addr,
7621 				    sd0 ? "worked" : "failed"));
7622 		}
7623 	}
7624 
7625 	/*
7626 	 * configure the requested device if LUN0 exists or we were
7627 	 * unable to determine the lun format to determine if LUN0
7628 	 * exists.
7629 	 */
7630 	if (sd0) {
7631 		sd = scsi_device_config(self,
7632 		    name, addr, SE_BUSCONFIG, &circ, NULL);
7633 	} else {
7634 		sd = NULL;
7635 		SCSI_HBA_LOG((_LOG(2), self, NULL,
7636 		    "%s@%s no lun 0 or filtered lun", name, addr));
7637 	}
7638 
7639 	/*
7640 	 * We know what we found, to reduce overhead we finish BUS_CONFIG_ONE
7641 	 * processing without calling back to the frameworks
7642 	 * ndi_busop_bus_config (unless we goto framework below).
7643 	 *
7644 	 * If the reference is to a driver name and we created a generic name
7645 	 * (bound to that driver) we will still succeed.  This is important
7646 	 * for correctly resolving old drivername references to device that now
7647 	 * uses a generic names across the transition to generic naming. This
7648 	 * is effectively an internal implementation of the NDI_DRIVERNAME flag.
7649 	 *
7650 	 * We also need to special case the resolve_pathname OBP boot-device
7651 	 * case (modrootloaded == 0) where reference is to a generic name but
7652 	 * we created a legacy driver name node by returning just returning
7653 	 * the node created.
7654 	 */
7655 	if (sd && sd->sd_dev &&
7656 	    ((strcmp(ddi_node_name(sd->sd_dev), name) == 0) ||
7657 	    (strcmp(ddi_driver_name(sd->sd_dev), name) == 0) ||
7658 	    (modrootloaded == 0)) &&
7659 	    (ndi_devi_online(sd->sd_dev,
7660 	    flags & NDI_NO_EVENT) == NDI_SUCCESS)) {
7661 
7662 		/* device attached, return devinfo node with hold */
7663 		ret = NDI_SUCCESS;
7664 		*childp = sd->sd_dev;
7665 		ndi_hold_devi(sd->sd_dev);
7666 	} else {
7667 		/*
7668 		 * In the process of failing we may have added nodes to the HBA
7669 		 * (self), clearing DEVI_MADE_CHILDREN. To reduce the overhead
7670 		 * associated with the frameworks reaction to this we clear the
7671 		 * flag here.
7672 		 */
7673 		mutex_enter(&DEVI(self)->devi_lock);
7674 		DEVI(self)->devi_flags &= ~DEVI_MADE_CHILDREN;
7675 		mutex_exit(&DEVI(self)->devi_lock);
7676 		ret = NDI_FAILURE;
7677 
7678 		/*
7679 		 * The framework may still be able to succeed with
7680 		 * with its GENERIC_PROP code.
7681 		 */
7682 		scsi_hba_devi_exit(self, circ);
7683 		if (flags & NDI_DRV_CONF_REPROBE)
7684 			flags |= NDI_CONFIG_REPROBE;
7685 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7686 		return (ndi_busop_bus_config(self, flags, BUS_CONFIG_ONE,
7687 		    (void *)arg, childp, 0));
7688 	}
7689 
7690 	scsi_hba_devi_exit(self, circ);
7691 	return (ret);
7692 }
7693 
7694 /*
7695  * Perform SCSI Parallel Interconnect bus_config
7696  */
7697 static int
7698 scsi_hba_bus_config_spi(dev_info_t *self, uint_t flags,
7699     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7700 {
7701 	int			ret;
7702 	int			mt;
7703 
7704 	/*
7705 	 * Enumerate scsi target devices: See if we are doing generic dynamic
7706 	 * enumeration: if driver.conf has not specified the 'scsi-enumeration'
7707 	 * knob then use the global scsi_enumeration knob.
7708 	 */
7709 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7710 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7711 	    "scsi-enumeration", scsi_enumeration);
7712 	mt |= scsi_hba_log_mt_disable;
7713 
7714 	if ((mt & SCSI_ENUMERATION_ENABLE) == 0) {
7715 		/*
7716 		 * Static driver.conf file enumeration:
7717 		 *
7718 		 * Force reprobe for BUS_CONFIG_ONE or when manually
7719 		 * reconfiguring via devfsadm(1m) to emulate deferred attach.
7720 		 * Reprobe only discovers driver.conf enumerated nodes, more
7721 		 * dynamic implementations probably require their own
7722 		 * bus_config.
7723 		 */
7724 		if ((op == BUS_CONFIG_ONE) || (flags & NDI_DRV_CONF_REPROBE))
7725 			flags |= NDI_CONFIG_REPROBE;
7726 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7727 		return (ndi_busop_bus_config(self, flags, op, arg, childp, 0));
7728 	}
7729 
7730 	if (scsi_hba_busconfig_debug)
7731 		flags |= NDI_DEVI_DEBUG;
7732 
7733 	/*
7734 	 * Generic spi dynamic bus config enumeration to discover and enumerate
7735 	 * the target device nodes we are looking for.
7736 	 */
7737 	switch (op) {
7738 	case BUS_CONFIG_ONE:	/* enumerate the named child */
7739 		ret = scsi_hba_bus_configone(self, flags, (char *)arg, childp);
7740 		break;
7741 
7742 	case BUS_CONFIG_ALL:	/* enumerate all children on the bus */
7743 	case BUS_CONFIG_DRIVER: /* enumerate all children that bind to driver */
7744 		SCSI_HBA_LOG((_LOG(3), self, NULL,
7745 		    "BUS_CONFIG_%s mt %x",
7746 		    (op == BUS_CONFIG_ALL) ? "ALL" : "DRIVER", mt));
7747 
7748 		/*
7749 		 * Enumerate targets on SCSI parallel interconnect and let the
7750 		 * framework finish the operation (attach the nodes).
7751 		 */
7752 		if ((ret = scsi_hba_bus_configall_spi(self, mt)) == NDI_SUCCESS)
7753 			ret = ndi_busop_bus_config(self, flags, op,
7754 			    arg, childp, 0);
7755 		break;
7756 
7757 	default:
7758 		ret = NDI_FAILURE;
7759 		break;
7760 	}
7761 	return (ret);
7762 }
7763 
7764 /*
7765  * Perform SCSI Parallel Interconnect bus_unconfig
7766  */
7767 static int
7768 scsi_hba_bus_unconfig_spi(dev_info_t *self, uint_t flags,
7769     ddi_bus_config_op_t op, void *arg)
7770 {
7771 	int	mt;
7772 	int	circ;
7773 	int	ret;
7774 
7775 	/*
7776 	 * See if we are doing generic dynamic enumeration: if driver.conf has
7777 	 * not specified the 'scsi-enumeration' knob then use the global
7778 	 * scsi_enumeration knob.
7779 	 */
7780 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7781 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7782 	    "scsi-enumeration", scsi_enumeration);
7783 	mt |= scsi_hba_log_mt_disable;
7784 
7785 	if ((mt & SCSI_ENUMERATION_ENABLE) == 0)
7786 		return (ndi_busop_bus_unconfig(self, flags, op, arg));
7787 
7788 	if (scsi_hba_busconfig_debug)
7789 		flags |= NDI_DEVI_DEBUG;
7790 
7791 	scsi_hba_devi_enter(self, &circ);
7792 	switch (op) {
7793 	case BUS_UNCONFIG_ONE:
7794 		SCSI_HBA_LOG((_LOG(3), self, NULL,
7795 		    "unconfig one: %s", (char *)arg));
7796 		ret = NDI_SUCCESS;
7797 		break;
7798 
7799 	case BUS_UNCONFIG_ALL:
7800 	case BUS_UNCONFIG_DRIVER:
7801 		ret = NDI_SUCCESS;
7802 		break;
7803 
7804 	default:
7805 		ret = NDI_FAILURE;
7806 		break;
7807 	}
7808 
7809 	/* Perform the generic default bus unconfig */
7810 	if (ret == NDI_SUCCESS)
7811 		ret = ndi_busop_bus_unconfig(self, flags, op, arg);
7812 
7813 	scsi_hba_devi_exit(self, circ);
7814 
7815 	return (ret);
7816 }
7817 
7818 static int
7819 scsi_hba_bus_config_tgtmap(dev_info_t *self, uint_t flags,
7820     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7821 {
7822 	int ret = NDI_FAILURE;
7823 
7824 	switch (op) {
7825 	case BUS_CONFIG_ONE:
7826 		ret = scsi_hba_bus_configone(self, flags, arg, childp);
7827 		break;
7828 
7829 	case BUS_CONFIG_ALL:
7830 	case BUS_CONFIG_DRIVER:
7831 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
7832 		break;
7833 
7834 	default:
7835 		break;
7836 	}
7837 
7838 	return (ret);
7839 }
7840 
7841 static int
7842 scsi_hba_bus_unconfig_tgtmap(dev_info_t *self, uint_t flags,
7843     ddi_bus_config_op_t op, void *arg)
7844 {
7845 	int ret = NDI_FAILURE;
7846 
7847 	switch (op) {
7848 	case BUS_UNCONFIG_ONE:
7849 	case BUS_UNCONFIG_DRIVER:
7850 	case BUS_UNCONFIG_ALL:
7851 		ret = NDI_SUCCESS;
7852 		break;
7853 	default:
7854 		break;
7855 	}
7856 
7857 	if (ret == NDI_SUCCESS) {
7858 		flags &= ~NDI_DEVI_REMOVE;
7859 		ret = ndi_busop_bus_unconfig(self, flags, op, arg);
7860 	}
7861 	return (ret);
7862 }
7863 
7864 static int
7865 scsi_hba_bus_config_iportmap(dev_info_t *self, uint_t flags,
7866     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7867 {
7868 	dev_info_t	*child;
7869 	int		circ;
7870 	int		ret = NDI_FAILURE;
7871 
7872 	/*
7873 	 * MPXIO is never a sure thing (and we have mixed children), so
7874 	 * set NDI_NDI_FALLBACK so that ndi_busop_bus_config will
7875 	 * search for both devinfo and pathinfo children.
7876 	 *
7877 	 * Future: Remove NDI_MDI_FALLBACK since devcfg.c now looks for
7878 	 * devinfo/pathinfo children in parallel (instead of old way of
7879 	 * looking for one form of child and then doing "fallback" to
7880 	 * look for other form of child).
7881 	 */
7882 	flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7883 	switch (op) {
7884 	case BUS_CONFIG_ONE:
7885 		scsi_hba_devi_enter(self, &circ);
7886 		/* create the iport node child */
7887 		if ((child = scsi_hba_bus_config_port(self, (char *)arg,
7888 		    SE_BUSCONFIG)) != NULL) {
7889 			if (childp) {
7890 				ndi_hold_devi(child);
7891 				*childp = child;
7892 			}
7893 			ret = NDI_SUCCESS;
7894 		}
7895 		scsi_hba_devi_exit(self, circ);
7896 		break;
7897 
7898 	case BUS_CONFIG_ALL:
7899 	case BUS_CONFIG_DRIVER:
7900 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
7901 		break;
7902 
7903 	default:
7904 		break;
7905 	}
7906 	return (ret);
7907 }
7908 
7909 static int
7910 scsi_hba_bus_unconfig_iportmap(dev_info_t *self, uint_t flags,
7911     ddi_bus_config_op_t op, void *arg)
7912 {
7913 	flags &= ~NDI_DEVI_REMOVE;
7914 	return (ndi_busop_bus_unconfig(self, flags, op, arg));
7915 }
7916 
7917 /*
7918  * SCSI HBA bus config enumeration entry point. Called via the bus_ops
7919  * bus_config entry point for all SCSA HBA drivers.
7920  *
7921  *  o	If an HBA implements its own bus_config via tran_bus_config then we
7922  *	invoke it. An HBA that implements its own tran_bus_config entry	point
7923  *	may still call back into common SCSA code bus_config code for:
7924  *
7925  *	o SPI bus_config (scsi_hba_bus_spi)
7926  *	o LUN and secondary function enumeration (scsi_hba_enum_lsf_of_t()).
7927  *	o configuration of a specific device (scsi_device_config).
7928  *	o determining 1275 SCSI nodename and compatible property
7929  *	  (scsi_hba_nodename_compatible_get/_free).
7930  *
7931  *   o	Otherwise we implement a SCSI parallel interface (spi) bus config.
7932  *
7933  * Return NDI_SUCCESS if we might have created a new node.
7934  * Return NDI_FAILURE if we definitely did not create a new node.
7935  */
7936 static int
7937 scsi_hba_bus_config(dev_info_t *self, uint_t flags,
7938     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7939 {
7940 	scsi_hba_tran_t	*tran;
7941 	int		ret;
7942 
7943 	/* make sure that we will not disappear */
7944 	ASSERT(DEVI(self)->devi_ref);
7945 
7946 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
7947 	if (tran == NULL) {
7948 		/* NULL tran driver.conf config (used by cmdk). */
7949 		if ((op == BUS_CONFIG_ONE) || (flags & NDI_DRV_CONF_REPROBE))
7950 			flags |= NDI_CONFIG_REPROBE;
7951 		return (ndi_busop_bus_config(self, flags, op, arg, childp, 0));
7952 	}
7953 
7954 	/* Check if self is HBA-only node. */
7955 	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
7956 		/* The bus_config request is to configure iports below HBA. */
7957 
7958 #ifdef	sparc
7959 		/*
7960 		 * Sparc's 'boot-device' OBP property value lacks an /iport@X/
7961 		 * component. Prior to the mount of root, we drive a disk@
7962 		 * BUS_CONFIG_ONE operatino down a level to resolve an
7963 		 * OBP 'boot-device' path.
7964 		 *
7965 		 * Future: Add (modrootloaded == 0) below, and insure that
7966 		 * all attempts bus_conf of 'bo_name' (in OBP form) occur
7967 		 * prior to 'modrootloaded = 1;' assignment in vfs_mountroot.
7968 		 */
7969 		if ((op == BUS_CONFIG_ONE) &&
7970 		    (strncmp((char *)arg, "disk@", strlen("disk@")) == 0)) {
7971 			return (scsi_hba_bus_config_prom_node(self,
7972 			    flags, arg, childp));
7973 		}
7974 #endif	/* sparc */
7975 
7976 		if (tran->tran_iportmap) {
7977 			/* config based on scsi_hba_iportmap API */
7978 			ret = scsi_hba_bus_config_iportmap(self,
7979 			    flags, op, arg, childp);
7980 		} else {
7981 			/* config based on 'iport_register' API */
7982 			ret = scsi_hba_bus_config_iports(self,
7983 			    flags, op, arg, childp);
7984 		}
7985 		return (ret);
7986 	}
7987 
7988 	/* Check to see how the iport/HBA does target/lun bus config. */
7989 	if (tran->tran_bus_config) {
7990 		/* HBA config based on Sun-private/legacy tran_bus_config */
7991 		ret = tran->tran_bus_config(self, flags, op, arg, childp);
7992 	} else if (tran->tran_tgtmap) {
7993 		/* SCSAv3 config based on scsi_hba_tgtmap_*() API */
7994 		ret =  scsi_hba_bus_config_tgtmap(self, flags, op, arg, childp);
7995 	} else {
7996 		/* SCSA config based on SCSI Parallel Interconnect */
7997 		ret = scsi_hba_bus_config_spi(self, flags, op, arg, childp);
7998 	}
7999 	return (ret);
8000 }
8001 
8002 /*
8003  * Called via the bus_ops bus_unconfig entry point for SCSI HBA drivers.
8004  */
8005 static int
8006 scsi_hba_bus_unconfig(dev_info_t *self, uint_t flags,
8007     ddi_bus_config_op_t op, void *arg)
8008 {
8009 	int		circ;
8010 	scsi_hba_tran_t	*tran;
8011 	int		ret;
8012 
8013 	tran = ddi_get_driver_private(self);
8014 	if (tran == NULL) {
8015 		/* NULL tran driver.conf unconfig (used by cmdk). */
8016 		return (ndi_busop_bus_unconfig(self, flags, op, arg));
8017 	}
8018 
8019 	/*
8020 	 * Purge barrier/probe node children. We do this prior to
8021 	 * tran_bus_unconfig in case the unconfig implementation calls back
8022 	 * into the common code at a different enumeration level, such a
8023 	 * scsi_device_config, which still creates barrier/probe nodes.
8024 	 */
8025 	scsi_hba_devi_enter(self, &circ);
8026 	scsi_hba_barrier_purge(self);
8027 	scsi_hba_devi_exit(self, circ);
8028 
8029 	/* Check if self is HBA-only node. */
8030 	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
8031 		/* The bus_config request is to unconfigure iports below HBA. */
8032 		if (tran->tran_iportmap) {
8033 			/* unconfig based on scsi_hba_iportmap API */
8034 			ret = scsi_hba_bus_unconfig_iportmap(self,
8035 			    flags, op, arg);
8036 		}
8037 		return (ret);
8038 	}
8039 
8040 	/* Check to see how the iport/HBA does target/lun bus unconfig. */
8041 	if (tran->tran_bus_unconfig) {
8042 		/* HBA unconfig based on Sun-private/legacy tran_bus_unconfig */
8043 		ret = tran->tran_bus_unconfig(self, flags, op, arg);
8044 	} else if (tran->tran_tgtmap) {
8045 		/* SCSAv3 unconfig based on scsi_hba_tgtmap_*() API */
8046 		ret = scsi_hba_bus_unconfig_tgtmap(self, flags, op, arg);
8047 	} else {
8048 		/* SCSA unconfig based on SCSI Parallel Interconnect */
8049 		ret = scsi_hba_bus_unconfig_spi(self, flags, op, arg);
8050 	}
8051 	return (ret);
8052 }
8053 
8054 static int
8055 scsi_tgtmap_scsi_config(void *arg, damap_t *mapp, damap_id_t tgtid)
8056 {
8057 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
8058 	dev_info_t		*self = tran->tran_iport_dip;
8059 	impl_scsi_tgtmap_t	*tgtmap;
8060 	char			*tgtaddr;
8061 	int			cfg_status, mt;
8062 
8063 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
8064 	tgtaddr = damap_id2addr(mapp, tgtid);
8065 
8066 	if (scsi_lunmap_create(self, tgtmap, tgtaddr) != DDI_SUCCESS) {
8067 		SCSI_HBA_LOG((_LOG_NF(WARN),
8068 		    "failed to create lunmap for %s", tgtaddr));
8069 	}
8070 
8071 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
8072 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
8073 	    scsi_enumeration);
8074 	mt |= scsi_hba_log_mt_disable;
8075 
8076 	cfg_status = scsi_hba_bus_config_taddr(self, tgtaddr, mt, SE_HP);
8077 	if (cfg_status != NDI_SUCCESS) {
8078 		SCSI_HBA_LOG((_LOGCFG, self, NULL, "%s @%s config status %d",
8079 		    damap_name(mapp), tgtaddr, cfg_status));
8080 		scsi_lunmap_destroy(self, tgtmap, tgtaddr);
8081 		return (DAM_FAILURE);
8082 	}
8083 
8084 	return (DAM_SUCCESS);
8085 }
8086 
8087 
8088 static int
8089 scsi_tgtmap_scsi_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
8090 {
8091 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
8092 	dev_info_t		*self = tran->tran_iport_dip;
8093 	impl_scsi_tgtmap_t	*tgtmap;
8094 	char			*tgt_addr;
8095 
8096 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
8097 	tgt_addr = damap_id2addr(mapp, tgtid);
8098 
8099 	SCSI_HBA_LOG((_LOGUNCFG, self, NULL, "%s @%s", damap_name(mapp),
8100 	    tgt_addr));
8101 	scsi_lunmap_destroy(self, tgtmap, tgt_addr);
8102 	return (DAM_SUCCESS);
8103 }
8104 
8105 static int
8106 scsi_tgtmap_smp_config(void *arg, damap_t *mapp, damap_id_t tgtid)
8107 {
8108 	scsi_hba_tran_t	*tran = (scsi_hba_tran_t *)arg;
8109 	dev_info_t	*self = tran->tran_iport_dip;
8110 	char		*addr;
8111 
8112 	addr = damap_id2addr(mapp, tgtid);
8113 	SCSI_HBA_LOG((_LOGCFG, self, NULL, "%s @%s", damap_name(mapp), addr));
8114 
8115 	return ((smp_hba_bus_config_taddr(self, addr) == NDI_SUCCESS) ?
8116 	    DAM_SUCCESS : DAM_FAILURE);
8117 }
8118 
8119 static int
8120 scsi_tgtmap_smp_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
8121 {
8122 	scsi_hba_tran_t	*tran = (scsi_hba_tran_t *)arg;
8123 	dev_info_t	*self = tran->tran_iport_dip;
8124 	char		*addr;
8125 	dev_info_t	*child;
8126 	char		nameaddr[SCSI_MAXNAMELEN];
8127 	int		circ;
8128 
8129 	addr = damap_id2addr(mapp, tgtid);
8130 	SCSI_HBA_LOG((_LOGUNCFG, self, NULL, "%s @%s", damap_name(mapp), addr));
8131 
8132 	(void) snprintf(nameaddr, sizeof (nameaddr), "smp@%s", addr);
8133 	scsi_hba_devi_enter(self, &circ);
8134 	if ((child = ndi_devi_findchild(self, nameaddr)) == NULL) {
8135 		scsi_hba_devi_exit(self, circ);
8136 		return (DAM_SUCCESS);
8137 	}
8138 
8139 	if (ndi_devi_offline(child,
8140 	    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) == DDI_SUCCESS) {
8141 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
8142 		    "devinfo smp@%s offlined and removed", addr));
8143 	} else if (ndi_devi_device_remove(child)) {
8144 		/* Offline/remove failed, note new device_remove */
8145 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
8146 		    "devinfo smp@%s offline failed, device_remove",
8147 		    addr));
8148 	}
8149 	scsi_hba_devi_exit(self, circ);
8150 	return (DAM_SUCCESS);
8151 }
8152 
8153 /* ARGSUSED1 */
8154 static void
8155 scsi_tgtmap_smp_activate(void *map_priv, char *tgt_addr, int addrid,
8156     void **tgt_privp)
8157 {
8158 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8159 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8160 
8161 	if (tgtmap->tgtmap_activate_cb) {
8162 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s activated",
8163 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE]),
8164 		    tgt_addr));
8165 
8166 		(*tgtmap->tgtmap_activate_cb)(tgtmap->tgtmap_mappriv,
8167 		    tgt_addr, SCSI_TGT_SMP_DEVICE, tgt_privp);
8168 	}
8169 }
8170 
8171 /* ARGSUSED1 */
8172 static void
8173 scsi_tgtmap_smp_deactivate(void *map_priv, char *tgt_addr, int addrid,
8174     void *tgt_privp, damap_deact_rsn_t deact_rsn)
8175 {
8176 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8177 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8178 
8179 	if (tgtmap->tgtmap_deactivate_cb) {
8180 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s deactivated",
8181 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE]),
8182 		    tgt_addr));
8183 
8184 		(*tgtmap->tgtmap_deactivate_cb)(tgtmap->tgtmap_mappriv,
8185 		    tgt_addr, SCSI_TGT_SMP_DEVICE, tgt_privp,
8186 		    (deact_rsn == DAMAP_DEACT_RSN_CFG_FAIL) ?
8187 		    SCSI_TGT_DEACT_RSN_CFG_FAIL : SCSI_TGT_DEACT_RSN_GONE);
8188 	}
8189 }
8190 
8191 /* ARGSUSED1 */
8192 static void
8193 scsi_tgtmap_scsi_activate(void *map_priv, char *tgt_addr, int addrid,
8194     void **tgt_privp)
8195 {
8196 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8197 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8198 
8199 	if (tgtmap->tgtmap_activate_cb) {
8200 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s activated",
8201 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]),
8202 		    tgt_addr));
8203 
8204 		(*tgtmap->tgtmap_activate_cb)(tgtmap->tgtmap_mappriv,
8205 		    tgt_addr, SCSI_TGT_SCSI_DEVICE, tgt_privp);
8206 	}
8207 }
8208 
8209 /* ARGSUSED1 */
8210 static void
8211 scsi_tgtmap_scsi_deactivate(void *map_priv, char *tgt_addr, int addrid,
8212     void *tgt_privp, damap_deact_rsn_t deact_rsn)
8213 {
8214 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8215 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8216 
8217 	if (tgtmap->tgtmap_deactivate_cb) {
8218 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s deactivated",
8219 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]),
8220 		    tgt_addr));
8221 
8222 		(*tgtmap->tgtmap_deactivate_cb)(tgtmap->tgtmap_mappriv,
8223 		    tgt_addr, SCSI_TGT_SCSI_DEVICE, tgt_privp,
8224 		    (deact_rsn == DAMAP_DEACT_RSN_CFG_FAIL) ?
8225 		    SCSI_TGT_DEACT_RSN_CFG_FAIL : SCSI_TGT_DEACT_RSN_GONE);
8226 	}
8227 }
8228 
8229 
8230 int
8231 scsi_hba_tgtmap_create(dev_info_t *self, scsi_tgtmap_mode_t mode,
8232     clock_t settle, void *tgtmap_priv, scsi_tgt_activate_cb_t activate_cb,
8233     scsi_tgt_deactivate_cb_t deactivate_cb, scsi_hba_tgtmap_t **handle)
8234 {
8235 	scsi_hba_tran_t		*tran;
8236 	damap_t			*mapp;
8237 	char			context[64];
8238 	impl_scsi_tgtmap_t	*tgtmap;
8239 	damap_rptmode_t		rpt_style;
8240 	char			*scsi_binding_set;
8241 	int			optflags;
8242 
8243 	if (self == NULL || settle == 0 || handle == NULL)
8244 		return (DDI_FAILURE);
8245 
8246 	*handle = NULL;
8247 
8248 	if (scsi_hba_iport_unit_address(self) == NULL)
8249 		return (DDI_FAILURE);
8250 
8251 	switch (mode) {
8252 	case SCSI_TM_FULLSET:
8253 		rpt_style = DAMAP_REPORT_FULLSET;
8254 		break;
8255 	case SCSI_TM_PERADDR:
8256 		rpt_style = DAMAP_REPORT_PERADDR;
8257 		break;
8258 	default:
8259 		return (DDI_FAILURE);
8260 	}
8261 
8262 	tran = (scsi_hba_tran_t *)ddi_get_driver_private(self);
8263 	ASSERT(tran);
8264 	if (tran == NULL)
8265 		return (DDI_FAILURE);
8266 
8267 	tgtmap = kmem_zalloc(sizeof (*tgtmap), KM_SLEEP);
8268 	tgtmap->tgtmap_tran = tran;
8269 	tgtmap->tgtmap_activate_cb = activate_cb;
8270 	tgtmap->tgtmap_deactivate_cb = deactivate_cb;
8271 	tgtmap->tgtmap_mappriv = tgtmap_priv;
8272 
8273 	optflags = (ddi_prop_get_int(DDI_DEV_T_ANY, self,
8274 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
8275 	    scsi_enumeration) & SCSI_ENUMERATION_MT_TARGET_DISABLE) ?
8276 	    DAMAP_SERIALCONFIG : DAMAP_MTCONFIG;
8277 
8278 	(void) snprintf(context, sizeof (context), "%s%d.tgtmap.scsi",
8279 	    ddi_driver_name(self), ddi_get_instance(self));
8280 	SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8281 	if (damap_create(context, rpt_style, optflags, settle,
8282 	    tgtmap, scsi_tgtmap_scsi_activate, scsi_tgtmap_scsi_deactivate,
8283 	    tran, scsi_tgtmap_scsi_config, scsi_tgtmap_scsi_unconfig,
8284 	    &mapp) != DAM_SUCCESS) {
8285 		kmem_free(tgtmap, sizeof (*tgtmap));
8286 		return (DDI_FAILURE);
8287 	}
8288 	tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE] = mapp;
8289 
8290 	(void) snprintf(context, sizeof (context), "%s%d.tgtmap.smp",
8291 	    ddi_driver_name(self), ddi_get_instance(self));
8292 	SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8293 	if (damap_create(context, rpt_style, optflags,
8294 	    settle, tgtmap, scsi_tgtmap_smp_activate,
8295 	    scsi_tgtmap_smp_deactivate,
8296 	    tran, scsi_tgtmap_smp_config, scsi_tgtmap_smp_unconfig,
8297 	    &mapp) != DAM_SUCCESS) {
8298 		damap_destroy(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]);
8299 		kmem_free(tgtmap, sizeof (*tgtmap));
8300 		return (DDI_FAILURE);
8301 	}
8302 	tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE] = mapp;
8303 
8304 	tran->tran_tgtmap = (scsi_hba_tgtmap_t *)tgtmap;
8305 	*handle = (scsi_hba_tgtmap_t *)tgtmap;
8306 
8307 	/*
8308 	 * We have now set tran_tgtmap, marking the tran as using tgtmap
8309 	 * enumeration services.  To prevent the generation of legacy spi
8310 	 * 'binding-set' compatible forms, remove the 'scsi-binding-set'
8311 	 * property.
8312 	 */
8313 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
8314 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-binding-set",
8315 	    &scsi_binding_set) == DDI_PROP_SUCCESS) {
8316 		if (strcmp(scsi_binding_set, scsi_binding_set_spi) == 0)
8317 			(void) ndi_prop_remove(DDI_DEV_T_NONE, self,
8318 			    "scsi-binding-set");
8319 		ddi_prop_free(scsi_binding_set);
8320 	}
8321 	return (DDI_SUCCESS);
8322 }
8323 
8324 void
8325 scsi_hba_tgtmap_destroy(scsi_hba_tgtmap_t *handle)
8326 {
8327 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8328 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8329 	int			i;
8330 
8331 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8332 		if (tgtmap->tgtmap_dam[i]) {
8333 			SCSI_HBA_LOG((_LOGTGT, self, NULL,
8334 			    "%s", damap_name(tgtmap->tgtmap_dam[i])));
8335 			damap_destroy(tgtmap->tgtmap_dam[i]);
8336 		}
8337 	}
8338 	kmem_free(tgtmap, sizeof (*tgtmap));
8339 }
8340 
8341 static int
8342 scsi_tgtmap_sync(scsi_hba_tgtmap_t *handle)
8343 {
8344 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8345 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8346 	int			empty = 1;
8347 	int			i;
8348 
8349 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8350 		if (tgtmap->tgtmap_dam[i]) {
8351 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s sync begin",
8352 			    damap_name(tgtmap->tgtmap_dam[i])));
8353 
8354 			/* return 1 if all maps ended up empty */
8355 			empty &= damap_sync(tgtmap->tgtmap_dam[i]);
8356 
8357 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s sync end",
8358 			    damap_name(tgtmap->tgtmap_dam[i])));
8359 		}
8360 	}
8361 	return (empty);
8362 }
8363 
8364 int
8365 scsi_hba_tgtmap_set_begin(scsi_hba_tgtmap_t *handle)
8366 {
8367 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8368 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8369 	char			*context;
8370 	int			rv = DDI_SUCCESS;
8371 	int			i;
8372 
8373 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8374 		if (tgtmap->tgtmap_dam[i] == NULL)
8375 			continue;
8376 
8377 		context = damap_name(tgtmap->tgtmap_dam[i]);
8378 
8379 		if (i == SCSI_TGT_SCSI_DEVICE) {
8380 			/*
8381 			 * In scsi_device context, so we have the 'context'
8382 			 * string, diagnose the case where the tgtmap caller
8383 			 * is failing to make forward progress, i.e. the caller
8384 			 * is never completing an observation, and calling
8385 			 * scsi_hbg_tgtmap_set_end. If this occurs, the solaris
8386 			 * target/lun state may be out of sync with hardware.
8387 			 */
8388 			if (tgtmap->tgtmap_reports++ >=
8389 			    scsi_hba_tgtmap_reports_max) {
8390 				tgtmap->tgtmap_noisy++;
8391 				if (tgtmap->tgtmap_noisy == 1)
8392 					SCSI_HBA_LOG((_LOG(WARN), self, NULL,
8393 					    "%s: failing to complete a tgtmap "
8394 					    "observation", context));
8395 			}
8396 		}
8397 
8398 		if (damap_addrset_begin(
8399 		    tgtmap->tgtmap_dam[i]) != DAM_SUCCESS) {
8400 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s FAIL", context));
8401 			rv = DDI_FAILURE;
8402 			continue;
8403 		}
8404 
8405 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8406 	}
8407 	return (rv);
8408 }
8409 
8410 
8411 int
8412 scsi_hba_tgtmap_set_add(scsi_hba_tgtmap_t *handle,
8413     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr, void *tgt_priv)
8414 {
8415 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8416 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8417 
8418 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8419 		return (DDI_FAILURE);
8420 
8421 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8422 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8423 
8424 	return ((damap_addrset_add(tgtmap->tgtmap_dam[tgt_type], tgt_addr,
8425 	    NULL, NULL, tgt_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8426 }
8427 
8428 /*ARGSUSED*/
8429 int
8430 scsi_hba_tgtmap_set_end(scsi_hba_tgtmap_t *handle, uint_t flags)
8431 {
8432 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8433 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8434 	char			*context;
8435 	int			rv = DDI_SUCCESS;
8436 	int			i;
8437 
8438 	tgtmap->tgtmap_reports = tgtmap->tgtmap_noisy = 0;
8439 
8440 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8441 		if (tgtmap->tgtmap_dam[i] == NULL)
8442 			continue;
8443 		context = damap_name(tgtmap->tgtmap_dam[i]);
8444 		if (damap_addrset_end(
8445 		    tgtmap->tgtmap_dam[i], 0) != DAM_SUCCESS) {
8446 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s FAIL", context));
8447 			rv = DDI_FAILURE;
8448 			continue;
8449 		}
8450 
8451 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8452 	}
8453 	return (rv);
8454 }
8455 
8456 int
8457 scsi_hba_tgtmap_tgt_add(scsi_hba_tgtmap_t *handle,
8458     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr, void *tgt_priv)
8459 
8460 {
8461 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8462 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8463 
8464 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8465 		return (DDI_FAILURE);
8466 
8467 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8468 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8469 
8470 	return ((damap_addr_add(tgtmap->tgtmap_dam[tgt_type], tgt_addr, NULL,
8471 	    NULL, tgt_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8472 }
8473 
8474 int
8475 scsi_hba_tgtmap_tgt_remove(scsi_hba_tgtmap_t *handle,
8476     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr)
8477 {
8478 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8479 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8480 
8481 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8482 		return (DDI_FAILURE);
8483 
8484 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8485 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8486 
8487 	return ((damap_addr_del(tgtmap->tgtmap_dam[tgt_type],
8488 	    tgt_addr) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8489 }
8490 
8491 int
8492 scsi_hba_tgtmap_lookup(scsi_hba_tgtmap_t *handle,
8493     char *tgt_addr, scsi_tgtmap_tgt_type_t *r_type)
8494 {
8495 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8496 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8497 	damap_id_t		tgtid;
8498 	int			i;
8499 
8500 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8501 		tgtid = damap_lookup(tgtmap->tgtmap_dam[i], tgt_addr);
8502 		if (tgtid != NODAM) {
8503 			*r_type = i;
8504 			SCSI_HBA_LOG((_LOG(3), self, NULL,
8505 			    "%s @%s found: type %d",
8506 			    damap_name(tgtmap->tgtmap_dam[i]), tgt_addr, i));
8507 			damap_id_rele(tgtmap->tgtmap_dam[i], tgtid);
8508 			return (DDI_SUCCESS);
8509 		}
8510 	}
8511 
8512 	SCSI_HBA_LOG((_LOG(3), self, NULL,
8513 	    "%s%d.tgtmap @%s not found",
8514 	    ddi_driver_name(self), ddi_get_instance(self), tgt_addr));
8515 	return (DDI_FAILURE);
8516 }
8517 
8518 /*
8519  * Return the unit-address of an 'iport' node, or NULL for non-iport node.
8520  */
8521 char *
8522 scsi_hba_iport_unit_address(dev_info_t *self)
8523 {
8524 	/*
8525 	 * NOTE: Since 'self' could be a SCSA iport node or a SCSA HBA node,
8526 	 * we can't use SCSA flavors: the flavor of a SCSA HBA node is not
8527 	 * established/owned by SCSA, it is established by the nexus that
8528 	 * created the SCSA HBA node (PCI) as a child.
8529 	 *
8530 	 * NOTE: If we want to support a node_name other than "iport" for
8531 	 * an iport node then we can add support for a "scsa-iport-node-name"
8532 	 * property on the SCSA HBA node.  A SCSA HBA driver would set this
8533 	 * property on the SCSA HBA node prior to using the iport API.
8534 	 */
8535 	if (strcmp(ddi_node_name(self), "iport") == 0)
8536 		return (ddi_get_name_addr(self));
8537 	else
8538 		return (NULL);
8539 }
8540 
8541 /*
8542  * Define a SCSI initiator port (bus/channel) for an HBA card that needs to
8543  * support multiple SCSI ports, but only has a single HBA devinfo node. This
8544  * function should be called from the HBA's attach(9E) implementation (when
8545  * processing the HBA devinfo node attach) after the number of SCSI ports on
8546  * the card is known or when the HBA driver DR handler detects a new port.
8547  * The function returns 0 on failure and 1 on success.
8548  *
8549  * The implementation will add the port value into the "scsi-iports" property
8550  * value maintained on the HBA node as. These properties are used by the generic
8551  * scsi bus_config implementation to dynamicaly enumerate the specified iport
8552  * children. The enumeration code will, on demand, create the appropriate
8553  * iport children with a SCSI_ADDR_PROP_IPORTUA unit address. This node will
8554  * bind to the same driver as the HBA node itself. This means that an HBA
8555  * driver that uses iports should expect probe(9E), attach(9E), and detach(9E)
8556  * calls on the iport children of the HBA.  If configuration for all ports was
8557  * already done during HBA node attach, the driver should just return
8558  * DDI_SUCCESS when confronted with an iport node.
8559  *
8560  * A maximum of 32 iport ports are supported per HBA devinfo node.
8561  *
8562  * A NULL "port" can be used to indicate that the framework should enumerate
8563  * target children on the HBA node itself, in addition to enumerating target
8564  * children on any iport nodes declared. There are two reasons that an HBA may
8565  * wish to have target children enumerated on both the HBA node and iport
8566  * node(s):
8567  *
8568  *   o  If, in the past, HBA hardware had only a single physical port but now
8569  *      supports multiple physical ports, the updated driver that supports
8570  *      multiple physical ports may want to avoid /devices path upgrade issues
8571  *      by enumerating the first physical port under the HBA instead of as a
8572  *      iport.
8573  *
8574  *   o  Some hardware RAID HBA controllers (mlx, chs, etc) support multiple
8575  *      SCSI physical ports configured so that various physical devices on
8576  *      the physical ports are amalgamated into virtual devices on a virtual
8577  *      port.  Amalgamated physical devices no longer appear to the host OS
8578  *      on the physical ports, but other non-amalgamated devices may still be
8579  *      visible on the physical ports.  These drivers use a model where the
8580  *      physical ports are iport nodes and the HBA node is the virtual port to
8581  *      the configured virtual devices.
8582  */
8583 int
8584 scsi_hba_iport_register(dev_info_t *self, char *port)
8585 {
8586 	unsigned int ports = 0;
8587 	int rval, i;
8588 	char **iports, **newiports;
8589 
8590 	ASSERT(self);
8591 	if (self == NULL)
8592 		return (DDI_FAILURE);
8593 
8594 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
8595 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
8596 	    &ports);
8597 
8598 	if (ports >= SCSI_HBA_MAX_IPORTS) {
8599 		ddi_prop_free(iports);
8600 		return (DDI_FAILURE);
8601 	}
8602 
8603 	if (rval == DDI_PROP_SUCCESS) {
8604 		for (i = 0; i < ports; i++) {
8605 			if (strcmp(port, iports[i]) == 0) {
8606 				/* iport already registered */
8607 				ddi_prop_free(iports);
8608 				return (DDI_SUCCESS);
8609 			}
8610 		}
8611 	}
8612 
8613 	newiports = kmem_alloc((sizeof (char *) * (ports + 1)), KM_SLEEP);
8614 
8615 	for (i = 0; i < ports; i++) {
8616 		newiports[i] = strdup(iports[i]);
8617 	}
8618 	newiports[ports] = strdup(port);
8619 	ports++;
8620 
8621 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, self,
8622 	    "scsi-iports", newiports, ports) != DDI_PROP_SUCCESS) {
8623 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
8624 		    "failed to establish %s %s",
8625 		    SCSI_ADDR_PROP_IPORTUA, port));
8626 		rval = DDI_FAILURE;
8627 	} else {
8628 		rval = DDI_SUCCESS;
8629 	}
8630 
8631 	/* If there is iport exist, free property */
8632 	if (ports > 1)
8633 		ddi_prop_free(iports);
8634 	for (i = 0; i < ports; i++) {
8635 		strfree(newiports[i]);
8636 	}
8637 	kmem_free(newiports, (sizeof (char *)) * ports);
8638 
8639 	return (rval);
8640 }
8641 
8642 /*
8643  * Check if the HBA has any scsi_hba_iport_register()ed children.
8644  */
8645 int
8646 scsi_hba_iport_exist(dev_info_t *self)
8647 {
8648 	unsigned int ports = 0;
8649 	char **iports;
8650 	int rval;
8651 
8652 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
8653 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
8654 	    &ports);
8655 
8656 	if (rval != DDI_PROP_SUCCESS)
8657 		return (0);
8658 
8659 	/* If there is now at least 1 iport, then iports is valid */
8660 	if (ports > 0) {
8661 		rval = 1;
8662 	} else
8663 		rval = 0;
8664 	ddi_prop_free(iports);
8665 
8666 	return (rval);
8667 }
8668 
8669 dev_info_t *
8670 scsi_hba_iport_find(dev_info_t *self, char *portnm)
8671 {
8672 	char		*addr = NULL;
8673 	char		**iports;
8674 	unsigned int	num_iports = 0;
8675 	int		rval = DDI_FAILURE;
8676 	int		i = 0;
8677 	dev_info_t	*child = NULL;
8678 
8679 	/* check to see if this is an HBA that defined scsi iports */
8680 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
8681 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
8682 	    &num_iports);
8683 
8684 	if (rval != DDI_SUCCESS) {
8685 		return (NULL);
8686 	}
8687 	ASSERT(num_iports > 0);
8688 
8689 	/* check to see if this port was registered */
8690 	for (i = 0; i < num_iports; i++) {
8691 		if (strcmp(iports[i], portnm) == 0)
8692 			break;
8693 	}
8694 
8695 	if (i == num_iports) {
8696 		child = NULL;
8697 		goto out;
8698 	}
8699 
8700 	addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
8701 	(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s", portnm);
8702 	rval = ndi_devi_config_one(self, addr, &child, NDI_NO_EVENT);
8703 	kmem_free(addr, SCSI_MAXNAMELEN);
8704 
8705 	if (rval != DDI_SUCCESS) {
8706 		child = NULL;
8707 	}
8708 out:
8709 	ddi_prop_free(iports);
8710 	return (child);
8711 }
8712 
8713 /*
8714  * Search/create the specified iport node
8715  */
8716 static dev_info_t *
8717 scsi_hba_bus_config_port(dev_info_t *self, char *nameaddr, scsi_enum_t se)
8718 {
8719 	dev_info_t	*child;		/* iport child of HBA node */
8720 	scsi_hba_tran_t	*tran;
8721 	char		*addr;
8722 	char		*compat;
8723 
8724 	/*
8725 	 * See if the iport node already exists.
8726 	 */
8727 	addr = nameaddr + strlen("iport@");
8728 	if (child = ndi_devi_findchild(self, nameaddr)) {
8729 		if (ndi_devi_device_isremoved(child)) {
8730 			if ((se == SE_HP) || !ndi_dev_is_hotplug_node(child)) {
8731 				if (ndi_devi_device_insert(child))
8732 					SCSI_HBA_LOG((_LOGCFG, self, NULL,
8733 					    "devinfo iport@%s device_reinsert",
8734 					    addr));
8735 			} else
8736 				return (NULL);
8737 		}
8738 		return (child);
8739 	}
8740 
8741 
8742 	/*
8743 	 * If config based on scsi_hba_iportmap API, only allow create
8744 	 * from hotplug.
8745 	 */
8746 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
8747 	ASSERT(tran);
8748 	if (tran->tran_iportmap && (se != SE_HP))
8749 		return (NULL);
8750 
8751 	/* allocate and initialize a new "iport" node */
8752 	ndi_devi_alloc_sleep(self, "iport",
8753 	    (se == SE_HP) ? DEVI_SID_HP_NODEID : DEVI_SID_NODEID,
8754 	    &child);
8755 	ASSERT(child);
8756 	/*
8757 	 * Set the flavor of the child to be IPORT flavored
8758 	 */
8759 	ndi_flavor_set(child, SCSA_FLAVOR_IPORT);
8760 
8761 	/*
8762 	 * Add the SCSI_ADDR_PROP_IPORTUA addressing property for this child.
8763 	 * This property is used to identify a iport node, and to represent the
8764 	 * nodes @addr form via node properties.
8765 	 *
8766 	 * Add "compatible" property to the "scsi-iport" node to cause it bind
8767 	 * to the same driver as the HBA  driver. Use the "driver" name
8768 	 * instead of the "binding name" to distinguish from hw node.
8769 	 *
8770 	 * Give the HBA a chance, via tran_set_name_prop, to set additional
8771 	 * iport node properties or to change the "compatible" binding
8772 	 * prior to init_child.
8773 	 *
8774 	 * NOTE: the order of these operations is important so that
8775 	 * scsi_hba_iport works when called.
8776 	 */
8777 	compat = (char *)ddi_driver_name(self);
8778 	if ((ndi_prop_update_string(DDI_DEV_T_NONE, child,
8779 	    SCSI_ADDR_PROP_IPORTUA, addr) != DDI_PROP_SUCCESS) ||
8780 	    (ndi_prop_update_string_array(DDI_DEV_T_NONE, child,
8781 	    "compatible", &compat, 1) != DDI_PROP_SUCCESS) ||
8782 	    ddi_pathname_obp_set(child, NULL) != DDI_SUCCESS) {
8783 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s failed dynamic decoration",
8784 		    nameaddr));
8785 		(void) ddi_remove_child(child, 0);
8786 		child = NULL;
8787 	} else {
8788 		/*
8789 		 * Online/attach in order to get events so devfsadm will
8790 		 * create public names.
8791 		 */
8792 		ndi_hold_devi(child);
8793 		if (ndi_devi_online(child, 0) != NDI_SUCCESS) {
8794 			ndi_rele_devi(child);
8795 			ndi_prop_remove_all(child);
8796 			(void) ndi_devi_free(child);
8797 			child = NULL;
8798 		} else
8799 			ndi_rele_devi(child);
8800 	}
8801 
8802 	return (child);
8803 }
8804 
8805 #ifdef	sparc
8806 /*
8807  * Future: When iportmap boot support is added, consider rewriting this to
8808  * perform a scsi_hba_bus_config(BUS_CONFIG_ALL) on self (HBA) followed by
8809  * a scsi_hba_bus_config(BUS_CONFIG_ONE) on each child of self (each iport).
8810  */
8811 /* ARGSUSED */
8812 static int
8813 scsi_hba_bus_config_prom_node(dev_info_t *self, uint_t flags,
8814     void *arg, dev_info_t **childp)
8815 {
8816 	char		**iports;
8817 	int		circ, i;
8818 	int		ret = NDI_FAILURE;
8819 	unsigned int	num_iports = 0;
8820 	dev_info_t	*pdip = NULL;
8821 	char		*addr = NULL;
8822 
8823 	/* check to see if this is an HBA that defined scsi iports */
8824 	ret = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
8825 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
8826 	    &num_iports);
8827 
8828 	if (ret != DDI_SUCCESS) {
8829 		return (ret);
8830 	}
8831 
8832 	ASSERT(num_iports > 0);
8833 
8834 	addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
8835 
8836 	ret = NDI_FAILURE;
8837 
8838 	scsi_hba_devi_enter(self, &circ);
8839 
8840 	/* create iport nodes for each scsi port/bus */
8841 	for (i = 0; i < num_iports; i++) {
8842 		bzero(addr, SCSI_MAXNAMELEN);
8843 		/* Prepend the iport name */
8844 		(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s",
8845 		    iports[i]);
8846 		if (pdip = scsi_hba_bus_config_port(self, addr, SE_BUSCONFIG)) {
8847 			if (ndi_busop_bus_config(self, NDI_NO_EVENT,
8848 			    BUS_CONFIG_ONE, addr, &pdip, 0) !=
8849 			    NDI_SUCCESS) {
8850 				continue;
8851 			}
8852 			/*
8853 			 * Try to configure child under iport see wehter
8854 			 * request node is the child of the iport node
8855 			 */
8856 			if (ndi_devi_config_one(pdip, arg, childp,
8857 			    NDI_NO_EVENT) == NDI_SUCCESS) {
8858 				ret = NDI_SUCCESS;
8859 				break;
8860 			}
8861 		}
8862 	}
8863 
8864 	scsi_hba_devi_exit(self, circ);
8865 
8866 	kmem_free(addr, SCSI_MAXNAMELEN);
8867 
8868 	ddi_prop_free(iports);
8869 
8870 	return (ret);
8871 }
8872 #endif
8873 
8874 /*
8875  * Perform iport port/bus bus_config.
8876  */
8877 static int
8878 scsi_hba_bus_config_iports(dev_info_t *self, uint_t flags,
8879     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
8880 {
8881 	char		*nameaddr, *addr;
8882 	char		**iports;
8883 	int		circ, i;
8884 	int		ret = NDI_FAILURE;
8885 	unsigned int	num_iports = 0;
8886 
8887 	/* check to see if this is an HBA that defined scsi iports */
8888 	ret = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
8889 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
8890 	    &num_iports);
8891 
8892 	if (ret != DDI_SUCCESS) {
8893 		return (ret);
8894 	}
8895 
8896 	ASSERT(num_iports > 0);
8897 
8898 	scsi_hba_devi_enter(self, &circ);
8899 
8900 	switch (op) {
8901 	case BUS_CONFIG_ONE:
8902 		/* return if this operation is not against an iport node */
8903 		nameaddr = (char *)arg;
8904 		if ((nameaddr == NULL) ||
8905 		    (strncmp(nameaddr, "iport@", strlen("iport@")) != 0)) {
8906 			ret = NDI_FAILURE;
8907 			scsi_hba_devi_exit(self, circ);
8908 			ddi_prop_free(iports);
8909 			return (ret);
8910 		}
8911 
8912 		/* parse the port number from "iport@%s" */
8913 		addr = nameaddr + strlen("iport@");
8914 
8915 		/* check to see if this port was registered */
8916 		for (i = 0; i < num_iports; i++) {
8917 			if (strcmp((iports[i]), addr) == 0)
8918 				break;
8919 		}
8920 
8921 		if (i == num_iports) {
8922 			ret = NDI_FAILURE;
8923 			break;
8924 		}
8925 
8926 		/* create the iport node child */
8927 		if (scsi_hba_bus_config_port(self, nameaddr, SE_BUSCONFIG)) {
8928 			ret = NDI_SUCCESS;
8929 		}
8930 		break;
8931 
8932 	case BUS_CONFIG_ALL:
8933 	case BUS_CONFIG_DRIVER:
8934 		addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
8935 		/* create iport nodes for each scsi port/bus */
8936 		for (i = 0; i < num_iports; i++) {
8937 			bzero(addr, SCSI_MAXNAMELEN);
8938 			/* Prepend the iport name */
8939 			(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s",
8940 			    iports[i]);
8941 			(void) scsi_hba_bus_config_port(self, addr,
8942 			    SE_BUSCONFIG);
8943 		}
8944 
8945 		kmem_free(addr, SCSI_MAXNAMELEN);
8946 		ret = NDI_SUCCESS;
8947 		break;
8948 	}
8949 	if (ret == NDI_SUCCESS) {
8950 #ifdef sparc
8951 		/*
8952 		 * Mask NDI_PROMNAME since PROM doesn't have iport
8953 		 * node at all.
8954 		 */
8955 		flags &= (~NDI_PROMNAME);
8956 #endif
8957 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
8958 		ret = ndi_busop_bus_config(self, flags, op,
8959 		    arg, childp, 0);
8960 	}
8961 	scsi_hba_devi_exit(self, circ);
8962 
8963 	ddi_prop_free(iports);
8964 
8965 	return (ret);
8966 }
8967 
8968 typedef struct impl_scsi_iportmap {
8969 	dev_info_t	*iportmap_hba_dip;
8970 	damap_t		*iportmap_dam;
8971 } impl_scsi_iportmap_t;
8972 
8973 static int
8974 scsi_iportmap_config(void *arg, damap_t *mapp, damap_id_t tgtid)
8975 {
8976 	dev_info_t	*self = (dev_info_t *)arg;
8977 	int		circ;
8978 	char		nameaddr[SCSI_MAXNAMELEN];
8979 	char		*iport_addr;
8980 	dev_info_t	*childp;
8981 
8982 	scsi_hba_devi_enter(self, &circ);
8983 
8984 	iport_addr = damap_id2addr(mapp, tgtid);
8985 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
8986 	    "%s @%s", damap_name(mapp), iport_addr));
8987 
8988 	(void) snprintf(nameaddr, sizeof (nameaddr), "iport@%s", iport_addr);
8989 	childp = scsi_hba_bus_config_port(self, nameaddr, SE_HP);
8990 	scsi_hba_devi_exit(self, circ);
8991 	return (childp != NULL ? DAM_SUCCESS : DAM_FAILURE);
8992 }
8993 
8994 static int
8995 scsi_iportmap_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
8996 {
8997 	dev_info_t	*self = arg;
8998 	dev_info_t	*childp;	/* iport child of HBA node */
8999 	int		circ, empty;
9000 	char		*addr;
9001 	char		nameaddr[SCSI_MAXNAMELEN];
9002 	scsi_hba_tran_t	*tran;
9003 
9004 	addr = damap_id2addr(mapp, tgtid);
9005 	SCSI_HBA_LOG((_LOGIPT, self, NULL, "%s @%s", damap_name(mapp), addr));
9006 
9007 	(void) snprintf(nameaddr, sizeof (nameaddr), "iport@%s", addr);
9008 	scsi_hba_devi_enter(self, &circ);
9009 	if ((childp = ndi_devi_findchild(self, nameaddr)) == NULL) {
9010 		scsi_hba_devi_exit(self, circ);
9011 		return (DAM_FAILURE);
9012 	}
9013 
9014 	tran = ddi_get_driver_private(childp);
9015 	ASSERT(tran);
9016 
9017 	ndi_hold_devi(childp);
9018 	scsi_hba_devi_exit(self, circ);
9019 
9020 	/*
9021 	 * A begin/end (clear) against the iport's
9022 	 * tgtmap will trigger unconfigure of all
9023 	 * targets on the iport.
9024 	 *
9025 	 * Future: This bit of code only works if the
9026 	 * target map reporting style is are full
9027 	 * reports and not per-address. Maybe we
9028 	 * should plan on handling this by
9029 	 * auto-unconfiguration when destroying the
9030 	 * target map(s).
9031 	 */
9032 	(void) scsi_hba_tgtmap_set_begin(tran->tran_tgtmap);
9033 	(void) scsi_hba_tgtmap_set_end(tran->tran_tgtmap, 0);
9034 
9035 	/* wait for unconfigure */
9036 	empty = scsi_tgtmap_sync(tran->tran_tgtmap);
9037 
9038 	scsi_hba_devi_enter(self, &circ);
9039 	ndi_rele_devi(childp);
9040 
9041 	/* If begin/end/sync ends in empty map, offline/remove. */
9042 	if (empty) {
9043 		if (ndi_devi_offline(childp,
9044 		    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) == DDI_SUCCESS) {
9045 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
9046 			    "devinfo iport@%s offlined and removed",
9047 			    addr));
9048 		} else if (ndi_devi_device_remove(childp)) {
9049 			/* Offline/rem failed, note new device_remove */
9050 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
9051 			    "devinfo iport@%s offline failed, "
9052 			    "device_remove", addr));
9053 		}
9054 	}
9055 	scsi_hba_devi_exit(self, circ);
9056 	return (empty ? DAM_SUCCESS : DAM_FAILURE);
9057 }
9058 
9059 
9060 int
9061 scsi_hba_iportmap_create(dev_info_t *self, clock_t settle,
9062     scsi_hba_iportmap_t **handle)
9063 {
9064 	scsi_hba_tran_t		*tran;
9065 	damap_t			*mapp;
9066 	char			context[64];
9067 	impl_scsi_iportmap_t	*iportmap;
9068 
9069 	if (self == NULL || settle == 0 || handle == NULL)
9070 		return (DDI_FAILURE);
9071 
9072 	*handle = NULL;
9073 
9074 	if (scsi_hba_iport_unit_address(self) != NULL)
9075 		return (DDI_FAILURE);
9076 
9077 	tran = (scsi_hba_tran_t *)ddi_get_driver_private(self);
9078 	ASSERT(tran);
9079 	if (tran == NULL)
9080 		return (DDI_FAILURE);
9081 
9082 	(void) snprintf(context, sizeof (context), "%s%d.iportmap",
9083 	    ddi_driver_name(self), ddi_get_instance(self));
9084 
9085 	if (damap_create(context, DAMAP_REPORT_PERADDR, DAMAP_SERIALCONFIG,
9086 	    settle, NULL, NULL, NULL, self,
9087 	    scsi_iportmap_config, scsi_iportmap_unconfig, &mapp) !=
9088 	    DAM_SUCCESS) {
9089 		return (DDI_FAILURE);
9090 	}
9091 	iportmap = kmem_zalloc(sizeof (*iportmap), KM_SLEEP);
9092 	iportmap->iportmap_hba_dip = self;
9093 	iportmap->iportmap_dam = mapp;
9094 
9095 	tran->tran_iportmap = (scsi_hba_iportmap_t *)iportmap;
9096 	*handle = (scsi_hba_iportmap_t *)iportmap;
9097 
9098 	SCSI_HBA_LOG((_LOGIPT, self, NULL, "%s", damap_name(mapp)));
9099 	return (DDI_SUCCESS);
9100 }
9101 
9102 void
9103 scsi_hba_iportmap_destroy(scsi_hba_iportmap_t *handle)
9104 {
9105 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9106 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9107 
9108 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9109 	    "%s", damap_name(iportmap->iportmap_dam)));
9110 
9111 	damap_destroy(iportmap->iportmap_dam);
9112 	kmem_free(iportmap, sizeof (*iportmap));
9113 }
9114 
9115 int
9116 scsi_hba_iportmap_iport_add(scsi_hba_iportmap_t *handle,
9117     char *iport_addr, void *iport_priv)
9118 {
9119 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9120 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9121 
9122 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9123 	    "%s @%s", damap_name(iportmap->iportmap_dam), iport_addr));
9124 
9125 	return ((damap_addr_add(iportmap->iportmap_dam, iport_addr, NULL,
9126 	    NULL, iport_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9127 }
9128 
9129 int
9130 scsi_hba_iportmap_iport_remove(scsi_hba_iportmap_t *handle,
9131     char *iport_addr)
9132 {
9133 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9134 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9135 
9136 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9137 	    "%s @%s", damap_name(iportmap->iportmap_dam), iport_addr));
9138 
9139 	return ((damap_addr_del(iportmap->iportmap_dam,
9140 	    iport_addr) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9141 }
9142 
9143 int
9144 scsi_hba_iportmap_lookup(scsi_hba_iportmap_t *handle,
9145     char *iport_addr)
9146 {
9147 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9148 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9149 	damap_id_t		iportid;
9150 
9151 	iportid = damap_lookup(iportmap->iportmap_dam, iport_addr);
9152 	if (iportid != NODAM) {
9153 		SCSI_HBA_LOG((_LOG(3), self, NULL,
9154 		    "%s @%s found",
9155 		    damap_name(iportmap->iportmap_dam), iport_addr));
9156 		damap_id_rele(iportmap->iportmap_dam, iportid);
9157 		return (DDI_SUCCESS);
9158 	}
9159 
9160 	SCSI_HBA_LOG((_LOG(3), self, NULL,
9161 	    "%s @%s not found",
9162 	    damap_name(iportmap->iportmap_dam), iport_addr));
9163 	return (DDI_FAILURE);
9164 }
9165 
9166 
9167 static int
9168 scsi_lunmap_config(void *arg, damap_t *lundam, damap_id_t lunid)
9169 {
9170 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)arg;
9171 	scsi_hba_tran_t		*tran = tgtmap->tgtmap_tran;
9172 	dev_info_t		*self = tran->tran_iport_dip;
9173 	char			*addr;
9174 
9175 	addr = damap_id2addr(lundam, lunid);
9176 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9177 	    "%s @%s", damap_name(lundam), addr));
9178 	if (scsi_hba_bus_configone_addr(self, addr, SE_HP) != NULL)
9179 		return (DAM_SUCCESS);
9180 	else
9181 		return (DAM_FAILURE);
9182 }
9183 
9184 static int
9185 scsi_lunmap_unconfig(void *arg, damap_t *lundam, damap_id_t lunid)
9186 {
9187 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)arg;
9188 	scsi_hba_tran_t		*tran = tgtmap->tgtmap_tran;
9189 	dev_info_t		*self = tran->tran_iport_dip;
9190 	char			*addr;
9191 
9192 	addr = damap_id2addr(lundam, lunid);
9193 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s @%s", damap_name(lundam),
9194 	    addr));
9195 
9196 	scsi_hba_bus_unconfigone_addr(self, addr);
9197 	return (DAM_SUCCESS);
9198 }
9199 
9200 static int
9201 scsi_lunmap_create(dev_info_t *self, impl_scsi_tgtmap_t *tgtmap, char *taddr)
9202 {
9203 	char			context[64];
9204 	damap_t			*tgtdam;
9205 	damap_id_t		tgtid;
9206 	damap_t			*lundam;
9207 	int			optflags;
9208 
9209 	(void) snprintf(context, sizeof (context), "%s%d.%s.lunmap",
9210 	    ddi_driver_name(self), ddi_get_instance(self), taddr);
9211 
9212 	tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
9213 	tgtid = damap_lookup(tgtdam, taddr);
9214 	if (tgtid == NODAM) {
9215 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9216 		    "target %s not found", context));
9217 		return (DDI_FAILURE);
9218 	}
9219 
9220 	lundam = damap_id_priv_get(tgtdam, tgtid);
9221 	if (lundam) {
9222 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9223 		    "lunmap %s already created", context));
9224 		damap_id_rele(tgtdam, tgtid);
9225 		return (DDI_FAILURE);
9226 	}
9227 
9228 	optflags = (ddi_prop_get_int(DDI_DEV_T_ANY, self,
9229 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
9230 	    scsi_enumeration) & SCSI_ENUMERATION_MT_LUN_DISABLE) ?
9231 	    DAMAP_SERIALCONFIG : DAMAP_MTCONFIG;
9232 
9233 	/* NOTE: expected ref at tgtid/taddr: 2: caller + lookup. */
9234 	ASSERT(damap_id_ref(tgtdam, tgtid) == 2);
9235 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s creat, id %d ref %d",
9236 	    context, tgtid, damap_id_ref(tgtdam, tgtid)));
9237 
9238 	/* create lundam */
9239 	if (damap_create(context, DAMAP_REPORT_FULLSET, optflags, 1,
9240 	    NULL, NULL, NULL, tgtmap, scsi_lunmap_config, scsi_lunmap_unconfig,
9241 	    &lundam) != DAM_SUCCESS) {
9242 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9243 		    "%s create failed, id %d ref %d",
9244 		    context, tgtid, damap_id_ref(tgtdam, tgtid)));
9245 		damap_id_rele(tgtdam, tgtid);
9246 		return (DDI_FAILURE);
9247 	}
9248 
9249 	/*
9250 	 * Return with damap_id_hold at tgtid/taddr from damap_lookup to
9251 	 * account for damap_id_prv_set below.
9252 	 */
9253 	damap_id_priv_set(tgtdam, tgtid, lundam);
9254 	return (DDI_SUCCESS);
9255 }
9256 
9257 static void
9258 scsi_lunmap_destroy(dev_info_t *self, impl_scsi_tgtmap_t *tgtmap, char *taddr)
9259 {
9260 	char			context[64];
9261 	damap_t			*tgtdam;
9262 	damap_id_t		tgtid;
9263 	damap_t			*lundam;
9264 
9265 	(void) snprintf(context, sizeof (context), "%s%d.%s.lunmap",
9266 	    ddi_driver_name(self), ddi_get_instance(self), taddr);
9267 
9268 	tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
9269 	tgtid = damap_lookup(tgtdam, taddr);
9270 	if (tgtid == NODAM) {
9271 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9272 		    "target %s not found", context));
9273 		return;
9274 	}
9275 
9276 	lundam = (damap_t *)damap_id_priv_get(tgtdam, tgtid);
9277 	if (lundam == NULL) {
9278 		damap_id_rele(tgtdam, tgtid);		/* from damap_lookup */
9279 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9280 		    "lunmap %s already destroyed", context));
9281 		return;
9282 	}
9283 
9284 	/* NOTE: expected ref at tgtid/taddr: 3: priv_set + caller + lookup. */
9285 	ASSERT(damap_id_ref(tgtdam, tgtid) == 3);
9286 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s, id %d ref %d",
9287 	    damap_name(lundam), tgtid, damap_id_ref(tgtdam, tgtid)));
9288 
9289 	/*
9290 	 * A begin/end (clear) against a target's lunmap will trigger
9291 	 * unconfigure of all LUNs on the target.
9292 	 */
9293 	scsi_lunmap_set_begin(self, lundam);
9294 	scsi_lunmap_set_end(self, lundam);
9295 
9296 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9297 	    "%s sync begin", damap_name(lundam)));
9298 
9299 	(void) damap_sync(lundam);	/* wait for unconfigure */
9300 
9301 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9302 	    "%s sync end", damap_name(lundam)));
9303 
9304 	damap_id_priv_set(tgtdam, tgtid, NULL);
9305 
9306 	/* release hold established by damap_lookup above */
9307 	damap_id_rele(tgtdam, tgtid);
9308 
9309 	/* release hold established since scsi_lunmap_create() */
9310 	damap_id_rele(tgtdam, tgtid);
9311 
9312 	damap_destroy(lundam);
9313 }
9314 
9315 static void
9316 scsi_lunmap_set_begin(dev_info_t *self, damap_t *lundam)
9317 {
9318 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s", damap_name(lundam)));
9319 
9320 	(void) damap_addrset_begin(lundam);
9321 }
9322 
9323 static int
9324 scsi_lunmap_set_add(dev_info_t *self, damap_t *lundam,
9325     char *taddr, scsi_lun64_t lun64, int sfunc)
9326 {
9327 	char	ua[SCSI_MAXNAMELEN];
9328 
9329 	/* make unit address string form of "@taddr,lun[,sfunc]" */
9330 	if (sfunc == -1)
9331 		(void) snprintf(ua, sizeof (ua), "%s,%" PRIx64, taddr, lun64);
9332 	else
9333 		(void) snprintf(ua, sizeof (ua), "%s,%" PRIx64 ",%x",
9334 		    taddr, lun64, sfunc);
9335 
9336 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s @%s", damap_name(lundam), ua));
9337 
9338 	return ((damap_addrset_add(lundam, ua, NULL, NULL,
9339 	    NULL) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9340 }
9341 
9342 static void
9343 scsi_lunmap_set_end(dev_info_t *self, damap_t *lundam)
9344 {
9345 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s", damap_name(lundam)));
9346 
9347 	(void) damap_addrset_end(lundam, 0);
9348 }
9349 
9350 int
9351 scsi_lunmap_lookup(dev_info_t *self, damap_t *lundam, char *addr)
9352 {
9353 	damap_id_t		lunid;
9354 
9355 	if ((lunid = damap_lookup(lundam, addr)) != NODAM) {
9356 		SCSI_HBA_LOG((_LOG(3), self, NULL,
9357 		    "%s @%s found", damap_name(lundam), addr));
9358 		damap_id_rele(lundam, lunid);
9359 		return (DDI_SUCCESS);
9360 	}
9361 
9362 	SCSI_HBA_LOG((_LOG(3), self, NULL,
9363 	    "%s @%s not found", damap_name(lundam), addr));
9364 	return (DDI_FAILURE);
9365 }
9366 
9367 /*
9368  * phymap implementation
9369  *
9370  * We manage the timed aggregation of phys into a phy map * by creating a
9371  * SAS port construct (based upon 'name' of "local,remote" SAS addresses)
9372  * upon the first link up. As time goes on additional phys may join that port.
9373  * After an appropriate amount of settle time, we trigger the activation
9374  * callback which will then take the resultant bit mask of phys (phymask) in
9375  * the SAS port and use that to call back to the callback function
9376  * provided by the additional caller.
9377  *
9378  * We cross check to make sure that phys only exist in one SAS port at a
9379  * time by having soft state for each phy point back to the created
9380  * SAS port.
9381  *
9382  * NOTE: Make SAS_PHY_UA_LEN max(SAS_PHY_PHYMASK_LEN, SAS_PHY_NAME_LEN)
9383  * so we have enough space if sas_phymap_bitset2phymaskua phymask address
9384  * is already in use, and we end up using port name as unit address.
9385  */
9386 #define	SAS_PHY_NAME_FMT	"%" PRIx64 ",%" PRIx64
9387 #define	SAS_PHY_NAME_LEN	(16 + 1 + 16 + 1)
9388 #define	SAS_PHY_NPHY		(SAS2_PHYNUM_MAX + 1)
9389 #define	SAS_PHY_PHYMASK_LEN	((roundup(SAS_PHY_NPHY, 4)) / 4)
9390 #if	(SAS_PHY_PHYMASK_LEN > SAS_PHY_NAME_LEN)
9391 #define	SAS_PHY_UA_LEN		SAS_PHY_PHYMASK_LEN
9392 #else
9393 #define	SAS_PHY_UA_LEN		SAS_PHY_NAME_LEN
9394 #endif
9395 typedef struct impl_sas_phymap {
9396 	dev_info_t			*phymap_self;
9397 
9398 	kmutex_t			phymap_lock;
9399 	damap_t				*phymap_dam;
9400 	void				*phymap_phy2name;
9401 	ddi_soft_state_bystr		*phymap_name2phys;	/* bitset */
9402 	ddi_soft_state_bystr		*phymap_name2ua;
9403 	ddi_soft_state_bystr		*phymap_ua2name;
9404 
9405 	/* Noisy phy information - ensure forward progress for noisy phys */
9406 	int				phymap_phy_max;		/* max phy# */
9407 	int				phymap_reports;		/* per period */
9408 	int				phymap_reports_max;	/* scales */
9409 	int				phymap_phys_noisy;	/* detected */
9410 
9411 	/* These are for callbacks to the consumer. */
9412 	sas_phymap_activate_cb_t	phymap_acp;
9413 	sas_phymap_deactivate_cb_t	phymap_dcp;
9414 	void				*phymap_private;
9415 } impl_sas_phymap_t;
9416 
9417 /* Detect noisy phy: max changes per stabilization period per phy. */
9418 static int sas_phymap_phy_max_factor = 16;
9419 
9420 /*
9421  * Convert bitset into a unit-address string. The maximum string length would
9422  * be the maximum number of phys, rounded up by 4 and divided by 4.
9423  */
9424 static void
9425 sas_phymap_bitset2phymaskua(bitset_t *phys, char *buf)
9426 {
9427 	char			*ptr;
9428 	int			grp;
9429 	int			cur;
9430 	uint_t			bit;
9431 
9432 	bit = roundup(SAS_PHY_NPHY, 4);
9433 	grp = 4;
9434 	ptr = buf;
9435 	cur = 0;
9436 	do {
9437 		bit -= 1;
9438 		grp -= 1;
9439 		if (bitset_in_set(phys, bit)) {
9440 			cur |= (1 << grp);
9441 		}
9442 		if (grp == 0) {
9443 			grp = 4;
9444 			if (cur || ptr != buf) {
9445 				*ptr++ = "0123456789abcdef"[cur];
9446 				*ptr = 0;
9447 			}
9448 			cur = 0;
9449 		}
9450 	} while (bit != 0);
9451 	if (ptr == buf) {
9452 		*ptr++ = '0';
9453 		*ptr = 0;
9454 	}
9455 }
9456 
9457 static int
9458 sas_phymap_config(void *arg, damap_t *phydam, damap_id_t phyid)
9459 {
9460 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)arg;
9461 	char			*context = damap_name(phymap->phymap_dam);
9462 	char			*damn;
9463 	char			*name;
9464 	bitset_t		*phys;
9465 	char			*ua;
9466 	void			*ua_priv;
9467 
9468 	ASSERT(context);
9469 
9470 	mutex_enter(&phymap->phymap_lock);
9471 	phymap->phymap_reports = phymap->phymap_phys_noisy = 0;
9472 
9473 	/* Get the name ("local,remote" address string) from damap. */
9474 	damn = damap_id2addr(phydam, phyid);
9475 
9476 	/* Get the bitset of phys currently forming the port. */
9477 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, damn);
9478 	if (phys == NULL) {
9479 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: no phys",
9480 		    context, damn));
9481 		mutex_exit(&phymap->phymap_lock);
9482 		return (DAM_FAILURE);
9483 	}
9484 
9485 	/* allocate, get, and initialize name index of name2ua map */
9486 	if (ddi_soft_state_bystr_zalloc(phymap->phymap_name2ua, damn) !=
9487 	    DDI_SUCCESS) {
9488 		SCSI_HBA_LOG((_LOG_NF(WARN),
9489 		    "%s: %s: failed name2ua alloc", context, damn));
9490 		mutex_exit(&phymap->phymap_lock);
9491 		return (DAM_FAILURE);
9492 	}
9493 	if (!(ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, damn))) {
9494 		SCSI_HBA_LOG((_LOG_NF(WARN),
9495 		    "%s: %s: no name2ua", context, damn));
9496 		mutex_exit(&phymap->phymap_lock);
9497 		return (DAM_FAILURE);
9498 	}
9499 	sas_phymap_bitset2phymaskua(phys, ua);		/* set ua */
9500 
9501 	/* see if phymask ua index already allocated in ua2name map */
9502 	if (name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua)) {
9503 		/*
9504 		 * The 'phymask' sas_phymap_bitset2phymaskua ua is
9505 		 * already in use. This means that original phys have
9506 		 * formed into a new port, and that the original port
9507 		 * still exists (it has migrated to some completely
9508 		 * different set of phys). In this corner-case we use
9509 		 * "local,remote" name as a 'temporary' unit address.
9510 		 * Reset ua in name2ua map.
9511 		 */
9512 		(void) strlcpy(ua, damn, SAS_PHY_NAME_LEN);
9513 		name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9514 		if (name) {
9515 			/* The "local,remote" ua should be new... */
9516 			SCSI_HBA_LOG((_LOG_NF(WARN),
9517 			    "%s: %s ua already configured",
9518 			    context, ua));
9519 			mutex_exit(&phymap->phymap_lock);
9520 			return (DAM_SUCCESS);
9521 		}
9522 	}
9523 
9524 	/* allocate, get, and init ua index of ua2name map */
9525 	if (ddi_soft_state_bystr_zalloc(phymap->phymap_ua2name, ua) !=
9526 	    DDI_SUCCESS) {
9527 		ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
9528 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: failed ua2name alloc",
9529 		    context, damn));
9530 		mutex_exit(&phymap->phymap_lock);
9531 		return (DAM_FAILURE);
9532 	}
9533 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9534 	if (name == NULL) {
9535 		ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
9536 		SCSI_HBA_LOG((_LOG_NF(WARN),
9537 		    "%s: %s: no ua2name", context, ua));
9538 		mutex_exit(&phymap->phymap_lock);
9539 		return (DAM_FAILURE);
9540 	}
9541 
9542 	/* set name in ua2name map */
9543 	(void) strlcpy(name, damn, SAS_PHY_NAME_LEN);
9544 
9545 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9546 	    "%s: %s: ua %s: activate", context, damn, ua));
9547 
9548 	if (phymap->phymap_acp) {
9549 		/*
9550 		 * drop our lock and invoke the activation callback
9551 		 */
9552 		mutex_exit(&phymap->phymap_lock);
9553 		ua_priv = NULL;
9554 		(phymap->phymap_acp)(phymap->phymap_private, ua, &ua_priv);
9555 		mutex_enter(&phymap->phymap_lock);
9556 		damap_id_priv_set(phydam, phyid, ua_priv);
9557 	}
9558 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9559 	    "%s: %s: ua %s: activate complete", context, damn, ua));
9560 	mutex_exit(&phymap->phymap_lock);
9561 	return (DAM_SUCCESS);
9562 }
9563 
9564 /*ARGSUSED*/
9565 static int
9566 sas_phymap_unconfig(void *arg, damap_t *phydam, damap_id_t phyid)
9567 {
9568 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)arg;
9569 	char			*context = damap_name(phymap->phymap_dam);
9570 	char			*damn;
9571 	char			*ua;
9572 	void			*ua_priv;
9573 
9574 	ASSERT(context);
9575 
9576 	mutex_enter(&phymap->phymap_lock);
9577 	phymap->phymap_reports = phymap->phymap_phys_noisy = 0;
9578 
9579 	/* Get the name ("local,remote" address string) from damap. */
9580 	damn = damap_id2addr(phydam, phyid);
9581 
9582 	if (!(ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, damn))) {
9583 		SCSI_HBA_LOG((_LOG_NF(WARN),
9584 		    "%s: %s: no name2ua", context, damn));
9585 		mutex_exit(&phymap->phymap_lock);
9586 		return (DAM_FAILURE);
9587 	}
9588 
9589 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9590 	    "%s: %s: ua %s: deactivate", context, damn, ua));
9591 	if (phymap->phymap_dcp) {
9592 		ua_priv = damap_id_priv_get(phydam, phyid);
9593 		mutex_exit(&phymap->phymap_lock);
9594 		(phymap->phymap_dcp)(phymap->phymap_private, ua, ua_priv);
9595 		mutex_enter(&phymap->phymap_lock);
9596 	}
9597 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9598 	    "%s: %s: ua %s: deactivate complete", context, damn, ua));
9599 
9600 	/* delete ua<->name mappings */
9601 	ddi_soft_state_bystr_free(phymap->phymap_ua2name, ua);
9602 	ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
9603 	mutex_exit(&phymap->phymap_lock);
9604 	return (DAM_SUCCESS);
9605 }
9606 
9607 int
9608 sas_phymap_create(dev_info_t *self, clock_t settle,
9609     sas_phymap_mode_t mode, void *mode_argument, void *phymap_priv,
9610     sas_phymap_activate_cb_t  activate_cb,
9611     sas_phymap_deactivate_cb_t deactivate_cb,
9612     sas_phymap_t **handlep)
9613 {
9614 	_NOTE(ARGUNUSED(mode_argument));
9615 	char			context[64];
9616 	impl_sas_phymap_t	*phymap;
9617 
9618 	if (self == NULL || settle == 0 || handlep == NULL)
9619 		return (DDI_FAILURE);
9620 
9621 	if (mode != PHYMAP_MODE_SIMPLE)
9622 		return (DDI_FAILURE);
9623 
9624 	phymap = kmem_zalloc(sizeof (*phymap), KM_SLEEP);
9625 	phymap->phymap_self = self;
9626 	phymap->phymap_reports_max = 1 * sas_phymap_phy_max_factor;
9627 	phymap->phymap_acp = activate_cb;
9628 	phymap->phymap_dcp = deactivate_cb;
9629 	phymap->phymap_private = phymap_priv;
9630 	mutex_init(&phymap->phymap_lock, NULL, MUTEX_DRIVER, NULL);
9631 
9632 	(void) snprintf(context, sizeof (context), "%s%d.phymap",
9633 	    ddi_driver_name(self), ddi_get_instance(self));
9634 	SCSI_HBA_LOG((_LOGPHY, self, NULL, "%s", context));
9635 
9636 	if (damap_create(context, DAMAP_REPORT_PERADDR, DAMAP_SERIALCONFIG,
9637 	    settle, NULL, NULL, NULL,
9638 	    phymap, sas_phymap_config, sas_phymap_unconfig,
9639 	    &phymap->phymap_dam) != DAM_SUCCESS)
9640 		goto fail;
9641 
9642 	if (ddi_soft_state_init(&phymap->phymap_phy2name,
9643 	    SAS_PHY_NAME_LEN, SAS_PHY_NPHY) != 0)
9644 		goto fail;
9645 
9646 	if (ddi_soft_state_bystr_init(&phymap->phymap_name2phys,
9647 	    sizeof (bitset_t), SAS_PHY_NPHY) != 0)
9648 		goto fail;
9649 
9650 	if (ddi_soft_state_bystr_init(&phymap->phymap_name2ua,
9651 	    SAS_PHY_UA_LEN, SAS_PHY_NPHY) != 0)
9652 		goto fail;
9653 	if (ddi_soft_state_bystr_init(&phymap->phymap_ua2name,
9654 	    SAS_PHY_NAME_LEN, SAS_PHY_NPHY) != 0)
9655 		goto fail;
9656 
9657 	*handlep = (sas_phymap_t *)phymap;
9658 	return (DDI_SUCCESS);
9659 
9660 fail:	sas_phymap_destroy((sas_phymap_t *)phymap);
9661 	*handlep = NULL;
9662 	return (DDI_FAILURE);
9663 }
9664 
9665 void
9666 sas_phymap_destroy(sas_phymap_t *handle)
9667 {
9668 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9669 	char			*context;
9670 
9671 	context = phymap->phymap_dam ?
9672 	    damap_name(phymap->phymap_dam) : "unknown";
9673 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s", context));
9674 
9675 	if (phymap->phymap_ua2name)
9676 		ddi_soft_state_bystr_fini(&phymap->phymap_ua2name);
9677 	if (phymap->phymap_name2ua)
9678 		ddi_soft_state_bystr_fini(&phymap->phymap_name2ua);
9679 
9680 	if (phymap->phymap_name2phys)
9681 		ddi_soft_state_bystr_fini(&phymap->phymap_name2phys);
9682 
9683 	if (phymap->phymap_phy2name)
9684 		ddi_soft_state_fini(&phymap->phymap_phy2name);
9685 
9686 	if (phymap->phymap_dam)
9687 		damap_destroy(phymap->phymap_dam);
9688 	mutex_destroy(&phymap->phymap_lock);
9689 	kmem_free(phymap, sizeof (*phymap));
9690 }
9691 
9692 
9693 int
9694 sas_phymap_phy_add(sas_phymap_t *handle,
9695     int phy, uint64_t local, uint64_t remote)
9696 {
9697 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9698 	char			*context = damap_name(phymap->phymap_dam);
9699 	char			port[SAS_PHY_NAME_LEN];
9700 	char			*name;
9701 	bitset_t		*phys;
9702 	int			phy2name_allocated = 0;
9703 	int			name2phys_allocated = 0;
9704 	int			rv;
9705 
9706 	/* Create the SAS port name from the local and remote addresses. */
9707 	(void) snprintf(port, SAS_PHY_NAME_LEN, SAS_PHY_NAME_FMT,
9708 	    local, remote);
9709 
9710 	mutex_enter(&phymap->phymap_lock);
9711 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s: %s: add phy %d",
9712 	    context, port, phy));
9713 
9714 	/* Check for conflict in phy2name map */
9715 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
9716 	if (name) {
9717 		if (strcmp(name, port) != 0)
9718 			SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: add phy %d: "
9719 			    "already in %s", context, port, phy, name));
9720 		else
9721 			SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: add phy %d: "
9722 			    "duplicate add", context, port, phy));
9723 		mutex_exit(&phymap->phymap_lock);
9724 		return (DDI_FAILURE);
9725 	}
9726 
9727 	/* allocate, get, and initialize phy index of phy2name map */
9728 	if (ddi_soft_state_zalloc(
9729 	    phymap->phymap_phy2name, phy) != DDI_SUCCESS) {
9730 		SCSI_HBA_LOG((_LOG_NF(WARN),
9731 		    "%s: %s: failed phy2name alloc", context, port));
9732 		goto fail;
9733 	}
9734 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
9735 	if (name == NULL) {
9736 		SCSI_HBA_LOG((_LOG_NF(WARN),
9737 		    "%s: %s: no phy2name", context, port));
9738 		goto fail;
9739 	}
9740 	phy2name_allocated = 1;
9741 	(void) strlcpy(name, port, SAS_PHY_NAME_LEN);	/* set name */
9742 
9743 	/* Find/alloc, initialize name index of name2phys map */
9744 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
9745 	if (phys == NULL) {
9746 		if (ddi_soft_state_bystr_zalloc(phymap->phymap_name2phys,
9747 		    name) != DDI_SUCCESS) {
9748 			SCSI_HBA_LOG((_LOG_NF(WARN),
9749 			    "%s: %s: failed name2phys alloc", context, name));
9750 			goto fail;
9751 		}
9752 		phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
9753 		if (phys == NULL) {
9754 			SCSI_HBA_LOG((_LOG_NF(WARN),
9755 			    "%s: %s: no name2phys", context, name));
9756 			goto fail;
9757 		}
9758 		name2phys_allocated = 1;
9759 
9760 		/* Initialize bitset of phys */
9761 		bitset_init(phys);
9762 		bitset_resize(phys, SAS_PHY_NPHY);
9763 
9764 		/* NOTE: no bitset_fini of phys needed */
9765 	}
9766 	ASSERT(phys);
9767 
9768 	/* Reflect 'add' in phys bitset. */
9769 	if (bitset_atomic_test_and_add(phys, phy) < 0) {
9770 		/* It is an error if the phy was already recorded. */
9771 		SCSI_HBA_LOG((_LOG_NF(WARN),
9772 		    "%s: %s: phy bit %d already in port", context, name, phy));
9773 		goto fail;
9774 	}
9775 
9776 	/*
9777 	 * Check to see if we have a new phy_max for this map, and if so
9778 	 * scale phymap_reports_max to the new number of phys.
9779 	 */
9780 	if (phy > phymap->phymap_phy_max) {
9781 		phymap->phymap_phy_max = phy + 1;
9782 		phymap->phymap_reports_max = phymap->phymap_phy_max *
9783 		    sas_phymap_phy_max_factor;
9784 	}
9785 
9786 	/*
9787 	 * If we have not reached phymap_reports_max, start/restart the
9788 	 * activate timer. Otherwise, if phymap->phymap_reports add/rem reports
9789 	 * ever exceeds phymap_reports_max due to noisy phys, then report the
9790 	 * noise and force stabilization by stopping reports into the damap.
9791 	 *
9792 	 * The first config/unconfig callout out of the damap will reset
9793 	 * phymap->phymap_reports.
9794 	 */
9795 	rv = DDI_SUCCESS;
9796 	if (phymap->phymap_reports++ < phymap->phymap_reports_max) {
9797 		if (damap_addr_add(phymap->phymap_dam, name,
9798 		    NULL, NULL, NULL) == DAM_SUCCESS) {
9799 			SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9800 			    "%s: %s: damap_addr_add", context, name));
9801 		} else {
9802 			SCSI_HBA_LOG((_LOG_NF(WARN),
9803 			    "%s: %s: damap_addr_add failed", context, name));
9804 			rv = DDI_FAILURE;
9805 		}
9806 	} else {
9807 		phymap->phymap_phys_noisy++;
9808 		if (phymap->phymap_phys_noisy == 1)
9809 			SCSI_HBA_LOG((_LOG_NF(WARN),
9810 			    "%s: %s: noisy phys", context, name));
9811 	}
9812 	mutex_exit(&phymap->phymap_lock);
9813 	return (rv);
9814 
9815 fail:	if (phy2name_allocated)
9816 		ddi_soft_state_free(phymap->phymap_phy2name, phy);
9817 	if (name2phys_allocated)
9818 		ddi_soft_state_bystr_free(phymap->phymap_name2phys, name);
9819 	mutex_exit(&phymap->phymap_lock);
9820 	return (DDI_FAILURE);
9821 }
9822 
9823 int
9824 sas_phymap_phy_rem(sas_phymap_t *handle, int phy)
9825 {
9826 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9827 	char			*context = damap_name(phymap->phymap_dam);
9828 	char			*name;
9829 	bitset_t		*phys;
9830 	int			rv = DDI_FAILURE;
9831 
9832 	ASSERT(context);
9833 
9834 	mutex_enter(&phymap->phymap_lock);
9835 	phymap->phymap_reports++;
9836 
9837 	/* Find and free phy index of phy2name map */
9838 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
9839 	if (name == NULL) {
9840 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: rem phy %d: never added",
9841 		    context, phy));
9842 		goto fail;
9843 	}
9844 	/* NOTE: always free phy index of phy2name map before return... */
9845 
9846 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s: %s: rem phy %d",
9847 	    context, name, phy));
9848 
9849 	/* Get bitset of phys currently associated with named port. */
9850 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
9851 	if (phys == NULL) {
9852 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: name2phys failed",
9853 		    context, name));
9854 		goto fail;
9855 	}
9856 
9857 	/* Reflect 'rem' in phys bitset. */
9858 	if (bitset_atomic_test_and_del(phys, phy) < 0) {
9859 		/* It is an error if the phy wasn't one of the port's phys. */
9860 		SCSI_HBA_LOG((_LOG_NF(WARN),
9861 		    "%s: %s: phy bit %d not in port", context, name, phy));
9862 		goto fail;
9863 	}
9864 
9865 	/* If this was the last phy in the port, start the deactivate timer. */
9866 	if (bitset_is_null(phys) &&
9867 	    (phymap->phymap_reports++ < phymap->phymap_reports_max)) {
9868 		if (damap_addr_del(phymap->phymap_dam, name) == DAM_SUCCESS) {
9869 			SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9870 			    "%s: %s: damap_addr_del", context, name));
9871 		} else {
9872 			SCSI_HBA_LOG((_LOG_NF(WARN),
9873 			    "%s: %s: damap_addr_del failure", context, name));
9874 			goto fail;
9875 		}
9876 	}
9877 	rv = DDI_SUCCESS;
9878 
9879 	/* free phy index of phy2name map */
9880 fail:	if (name)
9881 		ddi_soft_state_free(phymap->phymap_phy2name, phy); /* free */
9882 	mutex_exit(&phymap->phymap_lock);
9883 	return (rv);
9884 }
9885 
9886 char *
9887 sas_phymap_lookup_ua(sas_phymap_t *handle, uint64_t local, uint64_t remote)
9888 {
9889 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9890 	char			*context = damap_name(phymap->phymap_dam);
9891 	char			name[SAS_PHY_NAME_LEN];
9892 	char			*ua;
9893 
9894 	ASSERT(context);
9895 
9896 	(void) snprintf(name, SAS_PHY_NAME_LEN, SAS_PHY_NAME_FMT,
9897 	    local, remote);
9898 
9899 	mutex_enter(&phymap->phymap_lock);
9900 	ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, name);
9901 	SCSI_HBA_LOG((_LOG(3), phymap->phymap_self, NULL,
9902 	    "%s: %s: ua %s", context, name, ua ? ua : "NULL"));
9903 	mutex_exit(&phymap->phymap_lock);
9904 	return (ua);
9905 }
9906 
9907 void *
9908 sas_phymap_lookup_uapriv(sas_phymap_t *handle, char *ua)
9909 {
9910 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9911 	char			*context = damap_name(phymap->phymap_dam);
9912 	char			*name;
9913 	damap_id_t		phyid;
9914 	void			*ua_priv = NULL;
9915 
9916 	ASSERT(context);
9917 
9918 	mutex_enter(&phymap->phymap_lock);
9919 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9920 	if (name) {
9921 		phyid = damap_lookup(phymap->phymap_dam, name);
9922 		if (phyid != NODAM) {
9923 			ua_priv = damap_id_priv_get(phymap->phymap_dam, phyid);
9924 			damap_id_rele(phymap->phymap_dam, phyid);
9925 		}
9926 	}
9927 
9928 	SCSI_HBA_LOG((_LOG(3), phymap->phymap_self, NULL,
9929 	    "%s: %s: ua %s ua_priv %p", context, name,
9930 	    ua ? ua : "NULL", ua_priv));
9931 	mutex_exit(&phymap->phymap_lock);
9932 	return (ua_priv);
9933 }
9934 
9935 int
9936 sas_phymap_uahasphys(sas_phymap_t *handle, char *ua)
9937 {
9938 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9939 	char			*name;
9940 	bitset_t		*phys;
9941 	int			n = 0;
9942 
9943 	mutex_enter(&phymap->phymap_lock);
9944 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9945 	if (name) {
9946 		phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
9947 		if (phys)
9948 			n = bitset_is_null(phys) ? 0 : 1;
9949 	}
9950 	mutex_exit(&phymap->phymap_lock);
9951 	return (n);
9952 }
9953 
9954 sas_phymap_phys_t *
9955 sas_phymap_ua2phys(sas_phymap_t *handle, char *ua)
9956 {
9957 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
9958 	char			*name;
9959 	bitset_t		*phys;
9960 	bitset_t		*cphys = NULL;
9961 
9962 	mutex_enter(&phymap->phymap_lock);
9963 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9964 	if (name == NULL)
9965 		goto fail;
9966 
9967 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
9968 	if (phys == NULL)
9969 		goto fail;
9970 
9971 	/* dup the phys and return */
9972 	cphys = kmem_alloc(sizeof (*cphys), KM_SLEEP);
9973 	bitset_init(cphys);
9974 	bitset_resize(cphys, SAS_PHY_NPHY);
9975 	bitset_copy(phys, cphys);
9976 
9977 fail:	mutex_exit(&phymap->phymap_lock);
9978 	return ((sas_phymap_phys_t *)cphys);
9979 }
9980 
9981 int
9982 sas_phymap_phys_next(sas_phymap_phys_t *phys)
9983 {
9984 	bitset_t	*cphys = (bitset_t *)phys;
9985 	int		phy;
9986 
9987 	phy = bitset_find(cphys);
9988 	if (phy != -1)
9989 		bitset_del(cphys, phy);
9990 	return (phy);
9991 }
9992 
9993 void
9994 sas_phymap_phys_free(sas_phymap_phys_t *phys)
9995 {
9996 	bitset_t	*cphys = (bitset_t *)phys;
9997 
9998 	if (cphys) {
9999 		bitset_fini(cphys);
10000 		kmem_free(cphys, sizeof (*cphys));
10001 	}
10002 }
10003 
10004 char *
10005 sas_phymap_phy2ua(sas_phymap_t *handle, int phy)
10006 {
10007 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10008 	char			*name;
10009 	char			*ua;
10010 	char			*rua = NULL;
10011 
10012 	mutex_enter(&phymap->phymap_lock);
10013 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
10014 	if (name == NULL)
10015 		goto fail;
10016 	ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, name);
10017 	if (ua == NULL)
10018 		goto fail;
10019 
10020 	/* dup the ua and return */
10021 	rua = strdup(ua);
10022 
10023 fail:	mutex_exit(&phymap->phymap_lock);
10024 	return (rua);
10025 }
10026 
10027 void
10028 sas_phymap_ua_free(char *ua)
10029 {
10030 	if (ua)
10031 		strfree(ua);
10032 }
10033