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