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