xref: /illumos-gate/usr/src/uts/common/io/scsi/impl/scsi_hba.c (revision 978d7443a924cda8208d6a10e72be89383bc7bec)
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 it 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 		if (rval == MDI_SUCCESS) {
6793 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6794 			    "pathinfo %s offlined and removed", spathname));
6795 		} else if (mdi_pi_device_remove(path)) {
6796 			/* Offline/remove failed, note new device_remove */
6797 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6798 			    "pathinfo %s offline failed, "
6799 			    "device_remove", spathname));
6800 		}
6801 		mdi_rele_path(path);
6802 		if ((rval == MDI_SUCCESS) &&
6803 		    (mdi_pi_free(path, 0) != MDI_SUCCESS)) {	/* REMOVE */
6804 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6805 			    "pathinfo %s mdi_pi_free failed, "
6806 			    "device_remove", spathname));
6807 			(void) mdi_pi_device_remove(path);
6808 		}
6809 	} else {
6810 		ASSERT((path == NULL) && (child == NULL));
6811 
6812 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
6813 		    "%s@%s not found", name ? name : "", addr));
6814 	}
6815 }
6816 
6817 /*
6818  * configure the device at the specified "@addr" address.
6819  */
6820 static struct scsi_device *
6821 scsi_hba_bus_configone_addr(dev_info_t *self, char *addr, scsi_enum_t se)
6822 {
6823 	int			circ;
6824 	struct scsi_device	*sd;
6825 
6826 	scsi_hba_devi_enter(self, &circ);
6827 	sd = scsi_device_config(self, NULL, addr, se, &circ, NULL);
6828 	scsi_hba_devi_exit(self, circ);
6829 	return (sd);
6830 }
6831 
6832 /*
6833  * unconfigure the device at the specified "@addr" address.
6834  */
6835 static void
6836 scsi_hba_bus_unconfigone_addr(dev_info_t *self, char *addr)
6837 {
6838 	int			circ;
6839 
6840 	scsi_hba_devi_enter(self, &circ);
6841 	(void) scsi_device_unconfig(self, NULL, addr, &circ);
6842 	scsi_hba_devi_exit(self, circ);
6843 }
6844 
6845 /*
6846  * The bus_config_all operations are multi-threaded for performance. A
6847  * separate thread per target and per LUN is used. The config handle is used
6848  * to coordinate all the threads at a given level and the config thread data
6849  * contains the required information for a specific thread to identify what it
6850  * is processing and the handle under which this is being processed.
6851  */
6852 
6853 /* multi-threaded config handle */
6854 struct	scsi_hba_mte_h {
6855 	dev_info_t		*h_self;	/* initiator port */
6856 	int			h_thr_count;
6857 	kmutex_t		h_lock;
6858 	kcondvar_t		h_cv;
6859 };
6860 
6861 /* target of 'self' config thread data */
6862 struct scsi_hba_mte_td {
6863 	struct scsi_hba_mte_h	*td_h;
6864 	char			*td_taddr;	/* target port */
6865 	int			td_mt;
6866 	scsi_enum_t		td_se;
6867 };
6868 
6869 /* Invoke callback on a vector of taddrs from multiple threads */
6870 static void
6871 scsi_hba_thread_taddrs(dev_info_t *self, char **taddrs, int mt,
6872     scsi_enum_t se, void (*callback)(void *arg))
6873 {
6874 	struct scsi_hba_mte_h	*h;	/* HBA header */
6875 	struct scsi_hba_mte_td	*td;	/* target data */
6876 	char			**taddr;
6877 
6878 	/* allocate and initialize the handle */
6879 	h = kmem_zalloc(sizeof (*h), KM_SLEEP);
6880 	mutex_init(&h->h_lock, NULL, MUTEX_DEFAULT, NULL);
6881 	cv_init(&h->h_cv, NULL, CV_DEFAULT, NULL);
6882 	h->h_self = self;
6883 
6884 	/* loop over all the targets */
6885 	for (taddr = taddrs; *taddr; taddr++) {
6886 		/* allocate a thread data structure for target */
6887 		td = kmem_alloc(sizeof (*td), KM_SLEEP);
6888 		td->td_h = h;
6889 		td->td_taddr = *taddr;
6890 		td->td_mt = mt;
6891 		td->td_se = se;
6892 
6893 		/* process the target */
6894 		mutex_enter(&h->h_lock);
6895 		h->h_thr_count++;
6896 		mutex_exit(&h->h_lock);
6897 
6898 		if (mt & SCSI_ENUMERATION_MT_TARGET_DISABLE)
6899 			callback((void *)td);
6900 		else
6901 			(void) thread_create(NULL, 0, callback, (void *)td,
6902 			    0, &p0, TS_RUN, minclsyspri);
6903 	}
6904 
6905 	/* wait for all the target threads to complete */
6906 	mutex_enter(&h->h_lock);
6907 	while (h->h_thr_count > 0)
6908 		cv_wait(&h->h_cv, &h->h_lock);
6909 	mutex_exit(&h->h_lock);
6910 
6911 	/* free the handle */
6912 	cv_destroy(&h->h_cv);
6913 	mutex_destroy(&h->h_lock);
6914 	kmem_free(h, sizeof (*h));
6915 }
6916 
6917 
6918 /* lun/secondary function of lun0 config thread data */
6919 struct scsi_hba_mte_ld {
6920 	struct scsi_hba_mte_h	*ld_h;
6921 	char			*ld_taddr;	/* target port */
6922 	scsi_lun64_t		ld_lun64;	/* lun */
6923 	int			ld_sfunc;	/* secondary function */
6924 	scsi_enum_t		ld_se;
6925 };
6926 
6927 /*
6928  * Enumerate the LUNs and secondary functions of the specified target. The
6929  * target portion of the "@addr" is already represented as a string in the
6930  * thread data, we add a ",lun" representation to this and perform a
6931  * bus_configone byte of enumeration on that "@addr".
6932  */
6933 static void
6934 scsi_hba_enum_lsf_of_tgt_thr(void *arg)
6935 {
6936 	struct scsi_hba_mte_ld	*ld = (struct scsi_hba_mte_ld *)arg;
6937 	struct scsi_hba_mte_h	*h = ld->ld_h;
6938 	dev_info_t		*self = h->h_self;
6939 	char			addr[SCSI_MAXNAMELEN];
6940 
6941 	/* make string form of "@taddr,lun[,sfunc]" and see if it exists */
6942 	if (ld->ld_sfunc == -1)
6943 		(void) snprintf(addr, sizeof (addr),
6944 		    "%s,%" PRIx64, ld->ld_taddr, ld->ld_lun64);
6945 	else
6946 		(void) snprintf(addr, sizeof (addr),
6947 		    "%s,%" PRIx64 ",%x",
6948 		    ld->ld_taddr, ld->ld_lun64, ld->ld_sfunc);
6949 
6950 	/* configure device at that unit-address address */
6951 	(void) scsi_hba_bus_configone_addr(self, addr, ld->ld_se);
6952 
6953 	/* signal completion of this LUN thread to the target */
6954 	mutex_enter(&h->h_lock);
6955 	if (--h->h_thr_count == 0)
6956 		cv_broadcast(&h->h_cv);
6957 	mutex_exit(&h->h_lock);
6958 
6959 	/* free config thread data */
6960 	kmem_free(ld, sizeof (*ld));
6961 }
6962 
6963 /* Format of SCSI REPORT_LUNS report */
6964 typedef struct scsi_lunrpt {
6965 	uchar_t		lunrpt_len_msb;		/* # LUNs being reported */
6966 	uchar_t		lunrpt_len_mmsb;
6967 	uchar_t		lunrpt_len_mlsb;
6968 	uchar_t		lunrpt_len_lsb;
6969 	uchar_t		lunrpt_reserved[4];
6970 	scsi_lun_t	lunrpt_luns[1];		/* LUNs, variable size */
6971 } scsi_lunrpt_t;
6972 
6973 /*
6974  * scsi_device_reportluns()
6975  *
6976  * Callers of this routine should ensure that the 'sd0' scsi_device structure
6977  * and 'pi' path_instance specified are associated with a responding LUN0.
6978  * This should not be called for SCSI-1 devices.
6979  *
6980  * To get a LUN report, we must allocate a buffer. To know how big to make the
6981  * buffer, we must know the number of LUNs. To know the number of LUNs, we must
6982  * get a LUN report. We first issue a SCMD_REPORT_LUNS command using a
6983  * reasonably sized buffer that's big enough to report all LUNs for most
6984  * typical devices. If it turns out that we needed a bigger buffer, we attempt
6985  * to allocate a buffer of sufficient size, and reissue the command. If the
6986  * first command succeeds, but the second fails, we return whatever we were
6987  * able to get the first time. We return enough information for the caller to
6988  * tell whether he got all the LUNs or only a subset.
6989  *
6990  * If successful, we allocate an array of scsi_lun_t to hold the results. The
6991  * caller must kmem_free(*lunarrayp, *sizep) when finished with it. Upon
6992  * successful return return value is NDI_SUCCESS and:
6993  *
6994  *	*lunarrayp points to the allocated array,
6995  *	*nlunsp is the number of valid LUN entries in the array,
6996  *	*tlunsp is the total number of LUNs in the target,
6997  *	*sizep is the size of the lunarrayp array, which must be freed.
6998  *
6999  * If the *nlunsp is less than *tlunsp, then we were only able to retrieve a
7000  * subset of the total set of LUNs in the target.
7001  */
7002 static int
7003 scsi_device_reportluns(struct scsi_device *sd0, char *taddr, int pi,
7004     scsi_lun_t **lunarrayp, uint32_t *nlunsp, uint32_t *tlunsp, size_t *sizep)
7005 {
7006 	struct buf	*lunrpt_bp;
7007 	struct scsi_pkt *lunrpt_pkt;
7008 	scsi_lunrpt_t	*lunrpt;
7009 	uint32_t	bsize;
7010 	uint32_t	tluns, nluns;
7011 	int		default_maxluns = scsi_lunrpt_default_max;
7012 	dev_info_t	*child;
7013 
7014 	ASSERT(sd0 && lunarrayp && nlunsp && tlunsp && sizep);
7015 
7016 	/*
7017 	 * NOTE: child should only be used in SCSI_HBA_LOG context since with
7018 	 * vHCI enumeration it may be the vHCI 'client' devinfo child instead
7019 	 * of a child of the 'self' pHCI we are enumerating.
7020 	 */
7021 	child = sd0->sd_dev;
7022 
7023 	/* first try, look for up to scsi_lunrpt_default_max LUNs */
7024 	nluns = default_maxluns;
7025 
7026 again:	bsize = sizeof (struct scsi_lunrpt) +
7027 	    ((nluns - 1) * sizeof (struct scsi_lun));
7028 
7029 	lunrpt_bp = scsi_alloc_consistent_buf(&sd0->sd_address,
7030 	    (struct buf *)NULL, bsize, B_READ, SLEEP_FUNC, NULL);
7031 	if (lunrpt_bp == NULL) {
7032 		SCSI_HBA_LOG((_LOG(1), NULL, child, "failed alloc"));
7033 		return (NDI_NOMEM);
7034 	}
7035 
7036 	lunrpt_pkt = scsi_init_pkt(&sd0->sd_address,
7037 	    (struct scsi_pkt *)NULL, lunrpt_bp, CDB_GROUP5,
7038 	    sizeof (struct scsi_arq_status), 0, PKT_CONSISTENT,
7039 	    SLEEP_FUNC, NULL);
7040 	if (lunrpt_pkt == NULL) {
7041 		SCSI_HBA_LOG((_LOG(1), NULL, child, "failed init"));
7042 		scsi_free_consistent_buf(lunrpt_bp);
7043 		return (NDI_NOMEM);
7044 	}
7045 
7046 	(void) scsi_setup_cdb((union scsi_cdb *)lunrpt_pkt->pkt_cdbp,
7047 	    SCMD_REPORT_LUNS, 0, bsize, 0);
7048 
7049 	lunrpt_pkt->pkt_time = scsi_lunrpt_timeout;
7050 
7051 	/*
7052 	 * When sd0 is a vHCI scsi device, we need reportlun to be issued
7053 	 * against a specific LUN0 path_instance that we are enumerating.
7054 	 */
7055 	lunrpt_pkt->pkt_path_instance = pi;
7056 	lunrpt_pkt->pkt_flags |= FLAG_PKT_PATH_INSTANCE;
7057 
7058 	/*
7059 	 * NOTE: scsi_poll may not allow HBA specific recovery from TRAN_BUSY.
7060 	 */
7061 	if (scsi_poll(lunrpt_pkt) < 0) {
7062 		SCSI_HBA_LOG((_LOG(2), NULL, child, "reportlun not supported"));
7063 		scsi_destroy_pkt(lunrpt_pkt);
7064 		scsi_free_consistent_buf(lunrpt_bp);
7065 		return (NDI_FAILURE);
7066 	}
7067 
7068 	scsi_destroy_pkt(lunrpt_pkt);
7069 
7070 	lunrpt = (scsi_lunrpt_t *)lunrpt_bp->b_un.b_addr;
7071 
7072 	/* Compute the total number of LUNs in the target */
7073 	tluns = (((uint_t)lunrpt->lunrpt_len_msb << 24) |
7074 	    ((uint_t)lunrpt->lunrpt_len_mmsb << 16) |
7075 	    ((uint_t)lunrpt->lunrpt_len_mlsb << 8) |
7076 	    ((uint_t)lunrpt->lunrpt_len_lsb)) >> 3;
7077 
7078 	if (tluns == 0) {
7079 		/* Illegal response -- this target is broken */
7080 		SCSI_HBA_LOG((_LOG(1), NULL, child, "illegal tluns of zero"));
7081 		scsi_free_consistent_buf(lunrpt_bp);
7082 		return (DDI_NOT_WELL_FORMED);
7083 	}
7084 
7085 	if (tluns > nluns) {
7086 		/* have more than we allocated space for */
7087 		if (nluns == default_maxluns) {
7088 			/* first time around, reallocate larger */
7089 			scsi_free_consistent_buf(lunrpt_bp);
7090 			nluns = tluns;
7091 			goto again;
7092 		}
7093 
7094 		/* uh oh, we got a different tluns the second time! */
7095 		SCSI_HBA_LOG((_LOG(1), NULL, child,
7096 		    "tluns changed from %d to %d", nluns, tluns));
7097 	} else
7098 		nluns = tluns;
7099 
7100 	/*
7101 	 * Now we have:
7102 	 *	lunrpt_bp is the buffer we're using;
7103 	 *	tluns is the total number of LUNs the target says it has;
7104 	 *	nluns is the number of LUNs we were able to get into the buffer.
7105 	 *
7106 	 * Copy the data out of scarce iopb memory into regular kmem.
7107 	 * The caller must kmem_free(*lunarrayp, *sizep) when finished with it.
7108 	 */
7109 	*lunarrayp = (scsi_lun_t *)kmem_alloc(
7110 	    nluns * sizeof (scsi_lun_t), KM_SLEEP);
7111 	if (*lunarrayp == NULL) {
7112 		SCSI_HBA_LOG((_LOG(1), NULL, child, "NULL lunarray"));
7113 		scsi_free_consistent_buf(lunrpt_bp);
7114 		return (NDI_NOMEM);
7115 	}
7116 
7117 	*sizep = nluns * sizeof (scsi_lun_t);
7118 	*nlunsp = nluns;
7119 	*tlunsp = tluns;
7120 	bcopy((void *)&lunrpt->lunrpt_luns, (void *)*lunarrayp, *sizep);
7121 	scsi_free_consistent_buf(lunrpt_bp);
7122 	SCSI_HBA_LOG((_LOG(3), NULL, child,
7123 	    "@%s,0 path %d: %d/%d luns", taddr, pi, nluns, tluns));
7124 	return (NDI_SUCCESS);
7125 }
7126 
7127 /*
7128  * Enumerate all the LUNs and secondary functions of the specified 'taddr'
7129  * target port as accessed via 'self' pHCI.  Note that sd0 may be associated
7130  * with a child of the vHCI instead of 'self' - in this case the 'pi'
7131  * path_instance is used to ensure that the SCMD_REPORT_LUNS command is issued
7132  * through the 'self' pHCI path.
7133  *
7134  * We multi-thread across all the LUNs and secondary functions and enumerate
7135  * them. Which LUNs exist is based on SCMD_REPORT_LUNS data.
7136  *
7137  * The scsi_device we are called with should be for LUN0 and has been probed.
7138  *
7139  * This function is structured so that an HBA that has a different target
7140  * addressing structure can still use this function to enumerate the its
7141  * LUNs if it uses "taddr,lun" for its LUN space.
7142  *
7143  * We make assumptions about other LUNs associated with the target:
7144  *
7145  *	For SCSI-2 and SCSI-3 target we will issue the SCSI report_luns
7146  *	command. If this fails or we have a SCSI-1 then the number of
7147  *	LUNs is determined based on SCSI_OPTIONS_NLUNS. For a SCSI-1
7148  *	target we never probe above LUN 8, even if SCSI_OPTIONS_NLUNS
7149  *	indicates we should.
7150  *
7151  * HBA drivers wanting a different set of assumptions should implement their
7152  * own LUN enumeration code.
7153  */
7154 static int
7155 scsi_hba_enum_lsf_of_t(struct scsi_device *sd0,
7156     dev_info_t *self, char *taddr, int pi, int mt, scsi_enum_t se)
7157 {
7158 	dev_info_t		*child;
7159 	scsi_hba_tran_t		*tran;
7160 	impl_scsi_tgtmap_t	*tgtmap;
7161 	damap_id_t		tgtid;
7162 	damap_t			*tgtdam;
7163 	damap_t			*lundam = NULL;
7164 	struct scsi_hba_mte_h	*h;
7165 	struct scsi_hba_mte_ld	*ld;
7166 	int			aver;
7167 	scsi_lun_t		*lunp = NULL;
7168 	int			lun;
7169 	uint32_t		nluns;
7170 	uint32_t		tluns;
7171 	size_t			size;
7172 	scsi_lun64_t		lun64;
7173 	int			maxluns;
7174 
7175 	/*
7176 	 * If LUN0 failed then we have no other LUNs.
7177 	 *
7178 	 * NOTE: We need sd_inq to be valid to check ansi version. Since
7179 	 * scsi_unprobe is now a noop (sd_inq freeded in
7180 	 * scsi_busctl_uninitchild) sd_inq remains valid even if a target
7181 	 * driver detach(9E) occurs, resulting in a scsi_unprobe call
7182 	 * (sd_uninit_prevent keeps sd_inq valid by failing any
7183 	 * device_uninitchild attempts).
7184 	 */
7185 	ASSERT(sd0 && sd0->sd_uninit_prevent && sd0->sd_dev && sd0->sd_inq);
7186 	if ((sd0 == NULL) || (sd0->sd_dev == NULL) || (sd0->sd_inq == NULL)) {
7187 		SCSI_HBA_LOG((_LOG(1), NULL, sd0 ? sd0->sd_dev : NULL,
7188 		    "not setup correctly:%s%s%s",
7189 		    (sd0 == NULL) ? " device" : "",
7190 		    (sd0 && (sd0->sd_dev == NULL)) ? " dip" : "",
7191 		    (sd0 && (sd0->sd_inq == NULL)) ? " inq" : ""));
7192 		return (DDI_FAILURE);
7193 	}
7194 
7195 	/*
7196 	 * NOTE: child should only be used in SCSI_HBA_LOG context since with
7197 	 * vHCI enumeration it may be the vHCI 'client' devinfo child instead
7198 	 * of a child of the 'self' pHCI we are enumerating.
7199 	 */
7200 	child = sd0->sd_dev;
7201 
7202 	/* Determine if we are reporting lun observations into lunmap. */
7203 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
7204 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
7205 	if (tgtmap) {
7206 		tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
7207 		tgtid = damap_lookup(tgtdam, taddr);
7208 		if (tgtid != NODAM) {
7209 			lundam = damap_id_priv_get(tgtdam, tgtid);
7210 			damap_id_rele(tgtdam, tgtid);
7211 			ASSERT(lundam);
7212 		}
7213 	}
7214 
7215 	if (lundam) {
7216 		/* If using lunmap, start the observation */
7217 		scsi_lunmap_set_begin(self, lundam);
7218 	} else {
7219 		/* allocate and initialize the LUN handle */
7220 		h = kmem_zalloc(sizeof (*h), KM_SLEEP);
7221 		mutex_init(&h->h_lock, NULL, MUTEX_DEFAULT, NULL);
7222 		cv_init(&h->h_cv, NULL, CV_DEFAULT, NULL);
7223 		h->h_self = self;
7224 	}
7225 
7226 	/* See if SCMD_REPORT_LUNS works for SCSI-2 and beyond */
7227 	aver = sd0->sd_inq->inq_ansi;
7228 	if ((aver >= SCSI_VERSION_2) && (scsi_device_reportluns(sd0,
7229 	    taddr, pi, &lunp, &nluns, &tluns, &size) == NDI_SUCCESS)) {
7230 
7231 		ASSERT(lunp && (size > 0) && (nluns > 0) && (tluns > 0));
7232 
7233 		/* loop over the reported LUNs */
7234 		SCSI_HBA_LOG((_LOG(2), NULL, child,
7235 		    "@%s,0 path %d: enumerating %d reported lun%s", taddr, pi,
7236 		    nluns, nluns > 1 ? "s" : ""));
7237 
7238 		for (lun = 0; lun < nluns; lun++) {
7239 			lun64 = scsi_lun_to_lun64(lunp[lun]);
7240 
7241 			if (lundam) {
7242 				if (scsi_lunmap_set_add(self, lundam,
7243 				    taddr, lun64, -1) != DDI_SUCCESS) {
7244 					SCSI_HBA_LOG((_LOG_NF(WARN),
7245 					    "@%s,%" PRIx64 " failed to create",
7246 					    taddr, lun64));
7247 				}
7248 			} else {
7249 				if (lun64 == 0)
7250 					continue;
7251 
7252 				/* allocate a thread data structure for LUN */
7253 				ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7254 				ld->ld_h = h;
7255 				ld->ld_taddr = taddr;
7256 				ld->ld_lun64 = lun64;
7257 				ld->ld_sfunc = -1;
7258 				ld->ld_se = se;
7259 
7260 				/* process the LUN */
7261 				mutex_enter(&h->h_lock);
7262 				h->h_thr_count++;
7263 				mutex_exit(&h->h_lock);
7264 
7265 				if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7266 					scsi_hba_enum_lsf_of_tgt_thr(
7267 					    (void *)ld);
7268 				else
7269 					(void) thread_create(NULL, 0,
7270 					    scsi_hba_enum_lsf_of_tgt_thr,
7271 					    (void *)ld, 0, &p0, TS_RUN,
7272 					    minclsyspri);
7273 			}
7274 		}
7275 
7276 		/* free the LUN array allocated by scsi_device_reportluns */
7277 		kmem_free(lunp, size);
7278 	} else {
7279 		/* Determine the number of LUNs to enumerate. */
7280 		maxluns = scsi_get_scsi_maxluns(sd0);
7281 
7282 		/* Couldn't get SCMD_REPORT_LUNS data */
7283 		if (aver >= SCSI_VERSION_3) {
7284 			scsi_enumeration_failed(child, se, taddr, "report_lun");
7285 
7286 			/*
7287 			 * Based on calling context tunable, only enumerate one
7288 			 * lun (lun0) if scsi_device_reportluns() fails on a
7289 			 * SCSI_VERSION_3 or greater device.
7290 			 */
7291 			if (scsi_lunrpt_failed_do1lun & (1 << se))
7292 				maxluns = 1;
7293 		}
7294 
7295 		/* loop over possible LUNs, skipping LUN0 */
7296 		if (maxluns > 1)
7297 			SCSI_HBA_LOG((_LOG(2), NULL, child,
7298 			    "@%s,0 path %d: enumerating luns 1-%d", taddr, pi,
7299 			    maxluns - 1));
7300 		else
7301 			SCSI_HBA_LOG((_LOG(2), NULL, child,
7302 			    "@%s,0 path %d: enumerating just lun0", taddr, pi));
7303 
7304 		for (lun64 = 0; lun64 < maxluns; lun64++) {
7305 			if (lundam) {
7306 				if (scsi_lunmap_set_add(self, lundam,
7307 				    taddr, lun64, -1) != DDI_SUCCESS) {
7308 					SCSI_HBA_LOG((_LOG_NF(WARN),
7309 					    "@%s,%" PRIx64 " failed to create",
7310 					    taddr, lun64));
7311 				}
7312 			} else {
7313 				if (lun64 == 0)
7314 					continue;
7315 
7316 				/* allocate a thread data structure for LUN */
7317 				ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7318 				ld->ld_h = h;
7319 				ld->ld_taddr = taddr;
7320 				ld->ld_lun64 = lun64;
7321 				ld->ld_sfunc = -1;
7322 				ld->ld_se = se;
7323 
7324 				/* process the LUN */
7325 				mutex_enter(&h->h_lock);
7326 				h->h_thr_count++;
7327 				mutex_exit(&h->h_lock);
7328 				if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7329 					scsi_hba_enum_lsf_of_tgt_thr(
7330 					    (void *)ld);
7331 				else
7332 					(void) thread_create(NULL, 0,
7333 					    scsi_hba_enum_lsf_of_tgt_thr,
7334 					    (void *)ld, 0, &p0, TS_RUN,
7335 					    minclsyspri);
7336 			}
7337 		}
7338 	}
7339 
7340 	/*
7341 	 * If we have an embedded service as a secondary function on LUN0 and
7342 	 * the primary LUN0 function is different than the secondary function
7343 	 * then enumerate the secondary function. The sfunc value is the dtype
7344 	 * associated with the embedded service.
7345 	 *
7346 	 * inq_encserv: enclosure service and our dtype is not DTYPE_ESI
7347 	 * or DTYPE_UNKNOWN then create a separate DTYPE_ESI node for
7348 	 * enclosure service access.
7349 	 */
7350 	ASSERT(sd0->sd_inq);
7351 	if (sd0->sd_inq->inq_encserv &&
7352 	    ((sd0->sd_inq->inq_dtype & DTYPE_MASK) != DTYPE_UNKNOWN) &&
7353 	    ((sd0->sd_inq->inq_dtype & DTYPE_MASK) != DTYPE_ESI) &&
7354 	    ((sd0->sd_inq->inq_ansi >= SCSI_VERSION_3))) {
7355 		if (lundam) {
7356 			if (scsi_lunmap_set_add(self, lundam,
7357 			    taddr, 0, DTYPE_ESI) != DDI_SUCCESS) {
7358 				SCSI_HBA_LOG((_LOG_NF(WARN),
7359 				    "@%s,0,%x failed to create",
7360 				    taddr, DTYPE_ESI));
7361 			}
7362 		} else {
7363 			/* allocate a thread data structure for sfunc */
7364 			ld = kmem_alloc(sizeof (*ld), KM_SLEEP);
7365 			ld->ld_h = h;
7366 			ld->ld_taddr = taddr;
7367 			ld->ld_lun64 = 0;
7368 			ld->ld_sfunc = DTYPE_ESI;
7369 			ld->ld_se = se;
7370 
7371 			/* process the LUN */
7372 			mutex_enter(&h->h_lock);
7373 			h->h_thr_count++;
7374 			mutex_exit(&h->h_lock);
7375 			if (mt & SCSI_ENUMERATION_MT_LUN_DISABLE)
7376 				scsi_hba_enum_lsf_of_tgt_thr((void *)ld);
7377 			else
7378 				(void) thread_create(NULL, 0,
7379 				    scsi_hba_enum_lsf_of_tgt_thr, (void *)ld,
7380 				    0, &p0, TS_RUN, minclsyspri);
7381 		}
7382 	}
7383 
7384 	/*
7385 	 * Future: Add secondary function support for:
7386 	 *	inq_mchngr (DTYPE_CHANGER)
7387 	 *	inq_sccs (DTYPE_ARRAY_CTRL)
7388 	 */
7389 
7390 	if (lundam) {
7391 		/* If using lunmap, end the observation */
7392 		scsi_lunmap_set_end(self, lundam);
7393 	} else {
7394 		/* wait for all the LUN threads of this target to complete */
7395 		mutex_enter(&h->h_lock);
7396 		while (h->h_thr_count > 0)
7397 			cv_wait(&h->h_cv, &h->h_lock);
7398 		mutex_exit(&h->h_lock);
7399 
7400 		/* free the target handle */
7401 		cv_destroy(&h->h_cv);
7402 		mutex_destroy(&h->h_lock);
7403 		kmem_free(h, sizeof (*h));
7404 	}
7405 
7406 	return (DDI_SUCCESS);
7407 }
7408 
7409 /*
7410  * Enumerate LUN0 and all other LUNs and secondary functions associated with
7411  * the specified target address.
7412  *
7413  * Return NDI_SUCCESS if we might have created a new node.
7414  * Return NDI_FAILURE if we definitely did not create a new node.
7415  */
7416 static int
7417 scsi_hba_bus_config_taddr(dev_info_t *self, char *taddr, int mt, scsi_enum_t se)
7418 {
7419 	char			addr[SCSI_MAXNAMELEN];
7420 	struct scsi_device	*sd;
7421 	int			circ;
7422 	int			ret;
7423 	int			pi;
7424 
7425 	/* See if LUN0 of the specified target exists. */
7426 	(void) snprintf(addr, sizeof (addr), "%s,0", taddr);
7427 
7428 	scsi_hba_devi_enter(self, &circ);
7429 	sd = scsi_device_config(self, NULL, addr, se, &circ, &pi);
7430 
7431 	if (sd) {
7432 		/*
7433 		 * LUN0 exists, enumerate all the other LUNs.
7434 		 *
7435 		 * With vHCI enumeration, when 'self' is a pHCI the sd
7436 		 * scsi_device may be associated with the vHCI 'client'.
7437 		 * In this case 'pi' is the path_instance needed to
7438 		 * continue enumeration communication LUN0 via 'self'
7439 		 * pHCI and specific 'taddr' target address.
7440 		 *
7441 		 * We prevent the removal of LUN0 until we are done with
7442 		 * prevent/allow because we must exit the parent for
7443 		 * multi-threaded scsi_hba_enum_lsf_of_t().
7444 		 *
7445 		 * NOTE: scsi_unprobe is a noop, sd->sd_inq is valid until
7446 		 * device_uninitchild - so sd_uninit_prevent keeps sd_inq valid
7447 		 * by failing any device_uninitchild attempts.
7448 		 */
7449 		ret = NDI_SUCCESS;
7450 		sd->sd_uninit_prevent++;
7451 		scsi_hba_devi_exit(self, circ);
7452 
7453 		(void) scsi_hba_enum_lsf_of_t(sd, self, taddr, pi, mt, se);
7454 
7455 		scsi_hba_devi_enter(self, &circ);
7456 		sd->sd_uninit_prevent--;
7457 	} else
7458 		ret = NDI_FAILURE;
7459 	scsi_hba_devi_exit(self, circ);
7460 	return (ret);
7461 }
7462 
7463 /* Config callout from scsi_hba_thread_taddrs */
7464 static void
7465 scsi_hba_taddr_config_thr(void *arg)
7466 {
7467 	struct scsi_hba_mte_td	*td = (struct scsi_hba_mte_td *)arg;
7468 	struct scsi_hba_mte_h	*h = td->td_h;
7469 
7470 	(void) scsi_hba_bus_config_taddr(h->h_self, td->td_taddr,
7471 	    td->td_mt, td->td_se);
7472 
7473 	/* signal completion of this target thread to the HBA */
7474 	mutex_enter(&h->h_lock);
7475 	if (--h->h_thr_count == 0)
7476 		cv_broadcast(&h->h_cv);
7477 	mutex_exit(&h->h_lock);
7478 
7479 	/* free config thread data */
7480 	kmem_free(td, sizeof (*td));
7481 }
7482 
7483 /*
7484  * Enumerate all the children of the specified SCSI parallel interface (spi).
7485  * An HBA associated with a non-parallel scsi bus should be using another bus
7486  * level enumeration implementation (possibly their own) and calling
7487  * scsi_hba_bus_config_taddr to do enumeration of devices associated with a
7488  * particular target address.
7489  *
7490  * On an spi bus the targets are sequentially enumerated based on the
7491  * width of the bus. We also take care to try to skip the HBAs own initiator
7492  * id. See scsi_hba_enum_lsf_of_t() for LUN and secondary function enumeration.
7493  *
7494  * Return NDI_SUCCESS if we might have created a new node.
7495  * Return NDI_FAILURE if we definitely did not create a new node.
7496  *
7497  * Note: At some point we may want to expose this interface in transport.h
7498  * if we find an hba that implements bus_config but still uses spi-like target
7499  * addresses.
7500  */
7501 static int
7502 scsi_hba_bus_configall_spi(dev_info_t *self, int mt)
7503 {
7504 	int	options;
7505 	int	ntargets;
7506 	int	id;
7507 	int	tgt;
7508 	char	**taddrs;
7509 	char	**taddr;
7510 	char	*tbuf;
7511 
7512 	/*
7513 	 * Find the number of targets supported on the bus. Look at the per
7514 	 * bus scsi-options property on the HBA node and check its
7515 	 * SCSI_OPTIONS_WIDE setting.
7516 	 */
7517 	options = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7518 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-options", -1);
7519 	if ((options != -1) && ((options & SCSI_OPTIONS_WIDE) == 0))
7520 		ntargets = NTARGETS;			/* 8 */
7521 	else
7522 		ntargets = NTARGETS_WIDE;		/* 16 */
7523 
7524 	/*
7525 	 * Find the initiator-id for the HBA so we can skip that. We get the
7526 	 * cached value on the HBA node, established in scsi_hba_attach_setup.
7527 	 * If we were unable to determine the id then we rely on the HBA to
7528 	 * fail gracefully when asked to enumerate itself.
7529 	 */
7530 	id = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7531 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-initiator-id", -1);
7532 	if (id > ntargets) {
7533 		SCSI_HBA_LOG((_LOG(1), self, NULL,
7534 		    "'scsi-initiator-id' bogus for %d target bus: %d",
7535 		    ntargets, id));
7536 		id = -1;
7537 	}
7538 	SCSI_HBA_LOG((_LOG(2), self, NULL,
7539 	    "enumerating targets 0-%d skip %d", ntargets, id));
7540 
7541 	/* form vector of target addresses */
7542 	taddrs = kmem_zalloc(sizeof (char *) * (ntargets + 1), KM_SLEEP);
7543 	for (tgt = 0, taddr = taddrs; tgt < ntargets; tgt++) {
7544 		/* skip initiator */
7545 		if (tgt == id)
7546 			continue;
7547 
7548 		/* convert to string and enumerate the target address */
7549 		tbuf = kmem_alloc(((tgt/16) + 1) + 1, KM_SLEEP);
7550 		(void) sprintf(tbuf, "%x", tgt);
7551 		ASSERT(strlen(tbuf) == ((tgt/16) + 1));
7552 		*taddr++ = tbuf;
7553 	}
7554 
7555 	/* null terminate vector of target addresses */
7556 	*taddr = NULL;
7557 
7558 	/* configure vector of target addresses */
7559 	scsi_hba_thread_taddrs(self, taddrs, mt, SE_BUSCONFIG,
7560 	    scsi_hba_taddr_config_thr);
7561 
7562 	/* free vector of target addresses */
7563 	for (taddr = taddrs; *taddr; taddr++)
7564 		kmem_free(*taddr, strlen(*taddr) + 1);
7565 	kmem_free(taddrs, sizeof (char *) * (ntargets + 1));
7566 	return (NDI_SUCCESS);
7567 }
7568 
7569 /*
7570  * Transport independent bus_configone BUS_CONFIG_ONE implementation.  Takes
7571  * same arguments, minus op, as scsi_hba_bus_config(), tran_bus_config(),
7572  * and scsi_hba_bus_config_spi().
7573  */
7574 int
7575 scsi_hba_bus_configone(dev_info_t *self, uint_t flags, char *arg,
7576     dev_info_t **childp)
7577 {
7578 	int			ret;
7579 	int			circ;
7580 	char			*name, *addr;
7581 	char			*lcp;
7582 	char			sc1, sc2;
7583 	char			nameaddr[SCSI_MAXNAMELEN];
7584 	extern int		i_ndi_make_spec_children(dev_info_t *, uint_t);
7585 	struct scsi_device	*sd0, *sd;
7586 	scsi_lun64_t		lun64;
7587 	int			mt;
7588 
7589 	/* parse_name modifies arg1, we must duplicate "name@addr" */
7590 	(void) strcpy(nameaddr, arg);
7591 	i_ddi_parse_name(nameaddr, &name, &addr, NULL);
7592 
7593 	/* verify the form of the node - we need an @addr */
7594 	if ((name == NULL) || (addr == NULL) ||
7595 	    (*name == '\0') || (*addr == '\0')) {
7596 		/*
7597 		 * OBP may create ill formed template/stub/wild-card
7598 		 * nodes (no @addr) for legacy driver loading methods -
7599 		 * ignore them.
7600 		 */
7601 		SCSI_HBA_LOG((_LOG(2), self, NULL, "%s ill formed", arg));
7602 		return (NDI_FAILURE);
7603 	}
7604 
7605 	/*
7606 	 * Check to see if this is a non-scsi flavor configuration operation.
7607 	 */
7608 	if (strcmp(name, "smp") == 0) {
7609 		/*
7610 		 * Configure the child, and if we're successful return with
7611 		 * active hold.
7612 		 */
7613 		return (smp_hba_bus_config(self, addr, childp));
7614 	}
7615 
7616 	/*
7617 	 * The framework does not ensure the creation of driver.conf
7618 	 * nodes prior to calling a nexus bus_config. For legacy
7619 	 * support of driver.conf file nodes we want to create our
7620 	 * driver.conf file children now so that we can detect if we
7621 	 * are being asked to bus_configone one of these nodes.
7622 	 *
7623 	 * Needing driver.conf file nodes prior to bus config is unique
7624 	 * to scsi_enumeration mixed mode (legacy driver.conf and
7625 	 * dynamic SID node) support. There is no general need for the
7626 	 * framework to make driver.conf children prior to bus_config.
7627 	 *
7628 	 * We enter our HBA (self) prior to scsi_device_config, and
7629 	 * pass it our circ. The scsi_device_config may exit the
7630 	 * HBA around scsi_probe() operations to allow for parallelism.
7631 	 * This is done after the probe node "@addr" is available as a
7632 	 * barrier to prevent parallel probes of the same device. The
7633 	 * probe node is also configured in a way that it can't be
7634 	 * removed by the framework until we are done with it.
7635 	 *
7636 	 * NOTE: The framework is currently preventing many parallel
7637 	 * sibling operations (such as attaches), so the parallelism
7638 	 * we are providing is of marginal use until that is improved.
7639 	 * The most logical way to solve this would be to have separate
7640 	 * target and lun nodes. This would be a large change in the
7641 	 * format of /devices paths and is not being pursued at this
7642 	 * time. The need for parallelism will become more of an issue
7643 	 * with top-down attach for mpxio/vhci and for iSCSI support.
7644 	 * We may want to eventually want a dual mode implementation,
7645 	 * where the HBA determines if we should construct separate
7646 	 * target and lun devinfo nodes.
7647 	 */
7648 	scsi_hba_devi_enter(self, &circ);
7649 	SCSI_HBA_LOG((_LOG(4), self, NULL, "%s@%s config_one", name, addr));
7650 	(void) i_ndi_make_spec_children(self, flags);
7651 
7652 	/*
7653 	 * For bus_configone, we make sure that we can find LUN0
7654 	 * first. This allows the delayed probe/barrier deletion for a
7655 	 * non-existent LUN0 (if enabled in scsi_device_config) to
7656 	 * cover all LUNs on the target. This is done to minimize the
7657 	 * number of independent target selection timeouts that occur
7658 	 * when a target with many LUNs is no longer accessible
7659 	 * (powered off). This removes the need for target driver
7660 	 * probe cache implementations.
7661 	 *
7662 	 * This optimization may not be desirable in a pure bridge
7663 	 * environment where targets on the other side of the bridge
7664 	 * show up as LUNs to the host. If we ever need to support
7665 	 * such a configuration then we should consider implementing a
7666 	 * SCSI_OPTIONS_ILUN0 bit.
7667 	 *
7668 	 * NOTE: we are *not* applying any target limitation filtering
7669 	 * to bus_configone, which means that we are relying on the
7670 	 * HBA tran_tgt_init entry point invoked by scsi_busctl_initchild
7671 	 * to fail.
7672 	 */
7673 	sd0 = (struct scsi_device *)-1;
7674 	lcp = strchr(addr, ',');		/* "addr,lun[,sfunc]" */
7675 	if (lcp) {
7676 		/*
7677 		 * With "tgt,lun[,sfunc]" addressing, multiple addressing levels
7678 		 * have been compressed into single devinfo node unit-address.
7679 		 * This presents a mismatch - there is no bus_config to discover
7680 		 * LUNs below a specific target, the only choice is to
7681 		 * BUS_CONFIG_ALL the HBA. To support BUS_CONFIG_ALL_LUNS below
7682 		 * a specific target, a bus_configone with lun address of "*"
7683 		 * triggers lun discovery below a target.
7684 		 */
7685 		if (*(lcp + 1) == '*') {
7686 			mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7687 			    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7688 			    "scsi-enumeration", scsi_enumeration);
7689 			mt |= scsi_hba_log_mt_disable;
7690 
7691 			SCSI_HBA_LOG((_LOG(2), self, NULL,
7692 			    "%s@%s lun enumeration triggered", name, addr));
7693 			*lcp = '\0';		/* turn ',' into '\0' */
7694 			scsi_hba_devi_exit(self, circ);
7695 			(void) scsi_hba_bus_config_taddr(self, addr,
7696 			    mt, SE_BUSCONFIG);
7697 			return (NDI_FAILURE);
7698 		}
7699 
7700 		/* convert hex lun number from ascii */
7701 		lun64 = scsi_addr_to_lun64(lcp + 1);
7702 
7703 		if ((lun64 != 0) && (lun64 != SCSI_LUN64_ILLEGAL)) {
7704 			/*
7705 			 * configure ",0" lun first, saving off
7706 			 * original lun characters.
7707 			 */
7708 			sc1 = *(lcp + 1);
7709 			sc2 = *(lcp + 2);
7710 			*(lcp + 1) = '0';
7711 			*(lcp + 2) = '\0';
7712 			sd0 = scsi_device_config(self,
7713 			    NULL, addr, SE_BUSCONFIG, &circ, NULL);
7714 
7715 			/* restore original lun */
7716 			*(lcp + 1) = sc1;
7717 			*(lcp + 2) = sc2;
7718 
7719 			/*
7720 			 * Apply maxlun filtering.
7721 			 *
7722 			 * Future: We still have the kludged
7723 			 * scsi_check_ss2_LUN_limit() filtering off
7724 			 * scsi_probe() to catch bogus driver.conf
7725 			 * entries.
7726 			 */
7727 			if (sd0 && (lun64 < SCSI_32LUNS_PER_TARGET) &&
7728 			    (lun64 >= scsi_get_scsi_maxluns(sd0))) {
7729 				sd0 = NULL;
7730 				SCSI_HBA_LOG((_LOG(4), self, NULL,
7731 				    "%s@%s filtered", name, addr));
7732 			} else
7733 				SCSI_HBA_LOG((_LOG(4), self, NULL,
7734 				    "%s@%s lun 0 %s", name, addr,
7735 				    sd0 ? "worked" : "failed"));
7736 		}
7737 	}
7738 
7739 	/*
7740 	 * configure the requested device if LUN0 exists or we were
7741 	 * unable to determine the lun format to determine if LUN0
7742 	 * exists.
7743 	 */
7744 	if (sd0) {
7745 		sd = scsi_device_config(self,
7746 		    name, addr, SE_BUSCONFIG, &circ, NULL);
7747 	} else {
7748 		sd = NULL;
7749 		SCSI_HBA_LOG((_LOG(2), self, NULL,
7750 		    "%s@%s no lun 0 or filtered lun", name, addr));
7751 	}
7752 
7753 	/*
7754 	 * We know what we found, to reduce overhead we finish BUS_CONFIG_ONE
7755 	 * processing without calling back to the frameworks
7756 	 * ndi_busop_bus_config (unless we goto framework below).
7757 	 *
7758 	 * If the reference is to a driver name and we created a generic name
7759 	 * (bound to that driver) we will still succeed.  This is important
7760 	 * for correctly resolving old drivername references to device that now
7761 	 * uses a generic names across the transition to generic naming. This
7762 	 * is effectively an internal implementation of the NDI_DRIVERNAME flag.
7763 	 *
7764 	 * We also need to special case the resolve_pathname OBP boot-device
7765 	 * case (modrootloaded == 0) where reference is to a generic name but
7766 	 * we created a legacy driver name node by returning just returning
7767 	 * the node created.
7768 	 */
7769 	if (sd && sd->sd_dev &&
7770 	    ((strcmp(ddi_node_name(sd->sd_dev), name) == 0) ||
7771 	    (strcmp(ddi_driver_name(sd->sd_dev), name) == 0) ||
7772 	    (modrootloaded == 0)) &&
7773 	    (ndi_devi_online(sd->sd_dev,
7774 	    flags & NDI_NO_EVENT) == NDI_SUCCESS)) {
7775 
7776 		/* device attached, return devinfo node with hold */
7777 		ret = NDI_SUCCESS;
7778 		*childp = sd->sd_dev;
7779 		ndi_hold_devi(sd->sd_dev);
7780 	} else {
7781 		/*
7782 		 * In the process of failing we may have added nodes to the HBA
7783 		 * (self), clearing DEVI_MADE_CHILDREN. To reduce the overhead
7784 		 * associated with the frameworks reaction to this we clear the
7785 		 * flag here.
7786 		 */
7787 		mutex_enter(&DEVI(self)->devi_lock);
7788 		DEVI(self)->devi_flags &= ~DEVI_MADE_CHILDREN;
7789 		mutex_exit(&DEVI(self)->devi_lock);
7790 		ret = NDI_FAILURE;
7791 
7792 		/*
7793 		 * The framework may still be able to succeed with
7794 		 * with its GENERIC_PROP code.
7795 		 */
7796 		scsi_hba_devi_exit(self, circ);
7797 		if (flags & NDI_DRV_CONF_REPROBE)
7798 			flags |= NDI_CONFIG_REPROBE;
7799 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7800 		return (ndi_busop_bus_config(self, flags, BUS_CONFIG_ONE,
7801 		    (void *)arg, childp, 0));
7802 	}
7803 
7804 	scsi_hba_devi_exit(self, circ);
7805 	return (ret);
7806 }
7807 
7808 /*
7809  * Perform SCSI Parallel Interconnect bus_config
7810  */
7811 static int
7812 scsi_hba_bus_config_spi(dev_info_t *self, uint_t flags,
7813     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7814 {
7815 	int			ret;
7816 	int			mt;
7817 
7818 	/*
7819 	 * Enumerate scsi target devices: See if we are doing generic dynamic
7820 	 * enumeration: if driver.conf has not specified the 'scsi-enumeration'
7821 	 * knob then use the global scsi_enumeration knob.
7822 	 */
7823 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7824 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7825 	    "scsi-enumeration", scsi_enumeration);
7826 	mt |= scsi_hba_log_mt_disable;
7827 
7828 	if ((mt & SCSI_ENUMERATION_ENABLE) == 0) {
7829 		/*
7830 		 * Static driver.conf file enumeration:
7831 		 *
7832 		 * Force reprobe for BUS_CONFIG_ONE or when manually
7833 		 * reconfiguring via devfsadm(1m) to emulate deferred attach.
7834 		 * Reprobe only discovers driver.conf enumerated nodes, more
7835 		 * dynamic implementations probably require their own
7836 		 * bus_config.
7837 		 */
7838 		if ((op == BUS_CONFIG_ONE) || (flags & NDI_DRV_CONF_REPROBE))
7839 			flags |= NDI_CONFIG_REPROBE;
7840 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7841 		return (ndi_busop_bus_config(self, flags, op, arg, childp, 0));
7842 	}
7843 
7844 	if (scsi_hba_bus_config_debug)
7845 		flags |= NDI_DEVI_DEBUG;
7846 
7847 	/*
7848 	 * Generic spi dynamic bus config enumeration to discover and enumerate
7849 	 * the target device nodes we are looking for.
7850 	 */
7851 	switch (op) {
7852 	case BUS_CONFIG_ONE:	/* enumerate the named child */
7853 		ret = scsi_hba_bus_configone(self, flags, (char *)arg, childp);
7854 		break;
7855 
7856 	case BUS_CONFIG_ALL:	/* enumerate all children on the bus */
7857 	case BUS_CONFIG_DRIVER: /* enumerate all children that bind to driver */
7858 		SCSI_HBA_LOG((_LOG(3), self, NULL,
7859 		    "BUS_CONFIG_%s mt %x",
7860 		    (op == BUS_CONFIG_ALL) ? "ALL" : "DRIVER", mt));
7861 
7862 		/*
7863 		 * Enumerate targets on SCSI parallel interconnect and let the
7864 		 * framework finish the operation (attach the nodes).
7865 		 */
7866 		if ((ret = scsi_hba_bus_configall_spi(self, mt)) == NDI_SUCCESS)
7867 			ret = ndi_busop_bus_config(self, flags, op,
7868 			    arg, childp, 0);
7869 		break;
7870 
7871 	default:
7872 		ret = NDI_FAILURE;
7873 		break;
7874 	}
7875 	return (ret);
7876 }
7877 
7878 /*
7879  * Perform SCSI Parallel Interconnect bus_unconfig
7880  */
7881 static int
7882 scsi_hba_bus_unconfig_spi(dev_info_t *self, uint_t flags,
7883     ddi_bus_config_op_t op, void *arg)
7884 {
7885 	int	mt;
7886 	int	circ;
7887 	int	ret;
7888 
7889 	/*
7890 	 * See if we are doing generic dynamic enumeration: if driver.conf has
7891 	 * not specified the 'scsi-enumeration' knob then use the global
7892 	 * scsi_enumeration knob.
7893 	 */
7894 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
7895 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
7896 	    "scsi-enumeration", scsi_enumeration);
7897 	mt |= scsi_hba_log_mt_disable;
7898 
7899 	if ((mt & SCSI_ENUMERATION_ENABLE) == 0)
7900 		return (ndi_busop_bus_unconfig(self, flags, op, arg));
7901 
7902 	if (scsi_hba_bus_config_debug)
7903 		flags |= NDI_DEVI_DEBUG;
7904 
7905 	scsi_hba_devi_enter(self, &circ);
7906 	switch (op) {
7907 	case BUS_UNCONFIG_ONE:
7908 		SCSI_HBA_LOG((_LOG(3), self, NULL,
7909 		    "unconfig one: %s", (char *)arg));
7910 		ret = NDI_SUCCESS;
7911 		break;
7912 
7913 	case BUS_UNCONFIG_ALL:
7914 	case BUS_UNCONFIG_DRIVER:
7915 		ret = NDI_SUCCESS;
7916 		break;
7917 
7918 	default:
7919 		ret = NDI_FAILURE;
7920 		break;
7921 	}
7922 
7923 	/* Perform the generic default bus unconfig */
7924 	if (ret == NDI_SUCCESS)
7925 		ret = ndi_busop_bus_unconfig(self, flags, op, arg);
7926 
7927 	scsi_hba_devi_exit(self, circ);
7928 
7929 	return (ret);
7930 }
7931 
7932 static int
7933 scsi_hba_bus_config_tgtmap(dev_info_t *self, uint_t flags,
7934     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
7935 {
7936 	scsi_hba_tran_t		*tran;
7937 	impl_scsi_tgtmap_t	*tgtmap;
7938 	uint64_t		tsa = 0;	/* clock64_t */
7939 	int			maxdev;
7940 	int			sync_usec;
7941 	int			synced;
7942 	int			ret = NDI_FAILURE;
7943 
7944 	if ((op != BUS_CONFIG_ONE) && (op != BUS_CONFIG_ALL) &&
7945 	    (op != BUS_CONFIG_DRIVER))
7946 		goto out;
7947 
7948 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
7949 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
7950 	ASSERT(tgtmap);
7951 
7952 	/*
7953 	 * MPXIO is never a sure thing (and we have mixed children), so
7954 	 * set NDI_NDI_FALLBACK so that ndi_busop_bus_config will
7955 	 * search for both devinfo and pathinfo children.
7956 	 *
7957 	 * Future: Remove NDI_MDI_FALLBACK since devcfg.c now looks for
7958 	 * devinfo/pathinfo children in parallel (instead of old way of
7959 	 * looking for one form of child and then doing "fallback" to
7960 	 * look for other form of child).
7961 	 */
7962 	flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
7963 
7964 	/*
7965 	 * If bus_config occurred within the map create-to-hotplug_sync window,
7966 	 * we need the framework to wait for children that are physicaly
7967 	 * present at map create time to show up (via tgtmap hotplug config).
7968 	 *
7969 	 * The duration of this window is specified by the HBA driver at
7970 	 * scsi_hba_tgtmap_create(9F) time (during attach(9E)). Its
7971 	 * 'csync_usec' value is selected based on how long it takes the HBA
7972 	 * driver to get from map creation to initial observation for something
7973 	 * already plugged in. Estimate high, a low estimate can result in
7974 	 * devices not showing up correctly on first reference. The call to
7975 	 * ndi_busop_bus_config needs a timeout value large enough so that
7976 	 * the map sync call further down is not a noop (i.e. done against
7977 	 * an empty map when something is infact plugged in). With
7978 	 * BUS_CONFIG_ONE, the call to ndi_busop_bus_config will return as
7979 	 * soon as the desired device is enumerated via hotplug - so we are
7980 	 * not committed to waiting the entire time.
7981 	 *
7982 	 * We are typically outside the window, so timeout is 0.
7983 	 */
7984 	sync_usec = tgtmap->tgtmap_create_csync_usec;
7985 	if (tgtmap->tgtmap_create_window) {
7986 		tsa = ddi_get_lbolt64() - tgtmap->tgtmap_create_time;
7987 		if (tsa < drv_usectohz(sync_usec)) {
7988 			tsa = drv_usectohz(sync_usec) - tsa;
7989 			ret = ndi_busop_bus_config(self,
7990 			    flags, op, arg, childp, (clock_t)tsa);
7991 		} else
7992 			tsa = 0;	/* passed window */
7993 
7994 		/* First one out closes the window. */
7995 		tgtmap->tgtmap_create_window = 0;
7996 	} else if (op == BUS_CONFIG_ONE)
7997 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
7998 
7999 	/* Return if doing a BUS_CONFIG_ONE and we found what we want. */
8000 	if ((op == BUS_CONFIG_ONE) && (ret == NDI_SUCCESS))
8001 		goto out;		/* performance path */
8002 
8003 	/*
8004 	 * We sync if we were in the window, on the first bus_config_one, and
8005 	 * every bus_config_all (or bus_config_driver).
8006 	 */
8007 	if (tsa || (tgtmap->tgtmap_sync_cnt == 0) ||
8008 	    (op != BUS_CONFIG_ONE)) {
8009 		/*
8010 		 * Sync current observations in the map and look again.  We
8011 		 * place an upper bound on the amount of time we will wait for
8012 		 * sync to complete to avoid a bad device causing this
8013 		 * busconfig operation to hang.
8014 		 *
8015 		 * We are typically stable, so damap_sync returns immediately.
8016 		 *
8017 		 * Max time to wait for sync is settle_usec per possible device.
8018 		 */
8019 		tgtmap->tgtmap_sync_cnt++;
8020 		maxdev = damap_size(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]);
8021 		maxdev = (maxdev > scsi_hba_map_settle_f) ? maxdev :
8022 		    scsi_hba_map_settle_f;
8023 		sync_usec = maxdev * tgtmap->tgtmap_settle_usec;
8024 		synced = scsi_tgtmap_sync((scsi_hba_tgtmap_t *)tgtmap,
8025 		    sync_usec);
8026 		if (!synced)
8027 			SCSI_HBA_LOG((_LOGCFG, self, NULL,
8028 			    "tgtmap_sync timeout"));
8029 	} else
8030 		synced = -1;
8031 
8032 	if (op == BUS_CONFIG_ONE)
8033 		ret = scsi_hba_bus_configone(self, flags, arg, childp);
8034 	else
8035 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
8036 
8037 out:
8038 #ifdef	DEBUG
8039 	if (ret != NDI_SUCCESS) {
8040 		if (scsi_hba_bus_config_failure_msg ||
8041 		    scsi_hba_bus_config_failure_dbg) {
8042 			scsi_hba_bus_config_failure_msg--;
8043 			printf("%s%d: bus_config_tgtmap %p failure on %s: "
8044 			    "%d %d\n",
8045 			    ddi_driver_name(self), ddi_get_instance(self),
8046 			    (void *)tgtmap,
8047 			    (op == BUS_CONFIG_ONE) ? (char *)arg : "ALL",
8048 			    (int)tsa, synced);
8049 		}
8050 		if (scsi_hba_bus_config_failure_dbg) {
8051 			scsi_hba_bus_config_failure_dbg--;
8052 			debug_enter("config_tgtmap failure");
8053 		}
8054 	} else if (scsi_hba_bus_config_success_msg ||
8055 	    scsi_hba_bus_config_success_dbg) {
8056 		scsi_hba_bus_config_success_msg--;
8057 		printf("%s%d: bus_config_tgtmap %p success on %s: %d %d\n",
8058 		    ddi_driver_name(self), ddi_get_instance(self),
8059 		    (void *)tgtmap,
8060 		    (op == BUS_CONFIG_ONE) ? (char *)arg : "ALL",
8061 		    (int)tsa, synced);
8062 		if (scsi_hba_bus_config_success_dbg) {
8063 			scsi_hba_bus_config_success_dbg--;
8064 			debug_enter("config_tgtmap success");
8065 		}
8066 	}
8067 #endif	/* DEBUG */
8068 	return (ret);
8069 }
8070 
8071 static int
8072 scsi_hba_bus_unconfig_tgtmap(dev_info_t *self, uint_t flags,
8073     ddi_bus_config_op_t op, void *arg)
8074 {
8075 	int ret = NDI_FAILURE;
8076 
8077 	switch (op) {
8078 	case BUS_UNCONFIG_ONE:
8079 	case BUS_UNCONFIG_DRIVER:
8080 	case BUS_UNCONFIG_ALL:
8081 		ret = NDI_SUCCESS;
8082 		break;
8083 	default:
8084 		break;
8085 	}
8086 
8087 	if (ret == NDI_SUCCESS) {
8088 		flags &= ~NDI_DEVI_REMOVE;
8089 		ret = ndi_busop_bus_unconfig(self, flags, op, arg);
8090 	}
8091 	return (ret);
8092 }
8093 
8094 static int
8095 scsi_hba_bus_config_iportmap(dev_info_t *self, uint_t flags,
8096     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
8097 {
8098 	scsi_hba_tran_t		*tran;
8099 	impl_scsi_iportmap_t	*iportmap;
8100 	dev_info_t		*child;
8101 	int			circ;
8102 	uint64_t		tsa = 0;	/* clock64_t */
8103 	int			sync_usec;
8104 	int			synced;
8105 	int			ret = NDI_FAILURE;
8106 
8107 	if ((op != BUS_CONFIG_ONE) && (op != BUS_CONFIG_ALL) &&
8108 	    (op != BUS_CONFIG_DRIVER))
8109 		goto out;
8110 
8111 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
8112 	iportmap = (impl_scsi_iportmap_t *)tran->tran_iportmap;
8113 	ASSERT(iportmap);
8114 
8115 	/*
8116 	 * MPXIO is never a sure thing (and we have mixed children), so
8117 	 * set NDI_NDI_FALLBACK so that ndi_busop_bus_config will
8118 	 * search for both devinfo and pathinfo children.
8119 	 *
8120 	 * Future: Remove NDI_MDI_FALLBACK since devcfg.c now looks for
8121 	 * devinfo/pathinfo children in parallel (instead of old way of
8122 	 * looking for one form of child and then doing "fallback" to
8123 	 * look for other form of child).
8124 	 */
8125 	flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
8126 
8127 	/*
8128 	 * If bus_config occurred within the map create-to-hotplug_sync window,
8129 	 * we need the framework to wait for children that are physicaly
8130 	 * present at map create time to show up (via iportmap hotplug config).
8131 	 *
8132 	 * The duration of this window is specified by the HBA driver at
8133 	 * scsi_hba_iportmap_create(9F) time (during attach(9E)). Its
8134 	 * 'csync_usec' value is selected based on how long it takes the HBA
8135 	 * driver to get from map creation to initial observation for something
8136 	 * already plugged in. Estimate high, a low estimate can result in
8137 	 * devices not showing up correctly on first reference. The call to
8138 	 * ndi_busop_bus_config needs a timeout value large enough so that
8139 	 * the map sync call further down is not a noop (i.e. done against
8140 	 * an empty map when something is infact plugged in). With
8141 	 * BUS_CONFIG_ONE, the call to ndi_busop_bus_config will return as
8142 	 * soon as the desired device is enumerated via hotplug - so we are
8143 	 * not committed to waiting the entire time.
8144 	 *
8145 	 * We are typically outside the window, so timeout is 0.
8146 	 */
8147 	sync_usec = iportmap->iportmap_create_csync_usec;
8148 	if (iportmap->iportmap_create_window) {
8149 		tsa = ddi_get_lbolt64() - iportmap->iportmap_create_time;
8150 		if (tsa < drv_usectohz(sync_usec)) {
8151 			tsa = drv_usectohz(sync_usec) - tsa;
8152 			ret = ndi_busop_bus_config(self,
8153 			    flags, op, arg, childp, (clock_t)tsa);
8154 		} else
8155 			tsa = 0;	/* passed window */
8156 
8157 		/* First one out closes the window. */
8158 		iportmap->iportmap_create_window = 0;
8159 	} else if (op == BUS_CONFIG_ONE)
8160 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
8161 
8162 	/* Return if doing a BUS_CONFIG_ONE and we found what we want. */
8163 	if ((op == BUS_CONFIG_ONE) && (ret == NDI_SUCCESS))
8164 		goto out;		/* performance path */
8165 
8166 	/*
8167 	 * We sync if we were in the window, on the first bus_config_one, and
8168 	 * every bus_config_all (or bus_config_driver).
8169 	 */
8170 	if (tsa || (iportmap->iportmap_sync_cnt == 0) ||
8171 	    (op != BUS_CONFIG_ONE)) {
8172 		/*
8173 		 * Sync current observations in the map and look again.  We
8174 		 * place an upper bound on the amount of time we will wait for
8175 		 * sync to complete to avoid a bad device causing this
8176 		 * busconfig operation to hang.
8177 		 *
8178 		 * We are typically stable, so damap_sync returns immediately.
8179 		 *
8180 		 * Max time to wait for sync is settle_usec times settle factor.
8181 		 */
8182 		iportmap->iportmap_sync_cnt++;
8183 		synced = damap_sync(iportmap->iportmap_dam, sync_usec);
8184 		if (!synced)
8185 			SCSI_HBA_LOG((_LOGCFG, self, NULL,
8186 			    "iportmap_sync timeout"));
8187 	} else
8188 		synced = -1;
8189 
8190 	if (op == BUS_CONFIG_ONE) {
8191 		/* create the iport node child */
8192 		scsi_hba_devi_enter(self, &circ);
8193 		if ((child = scsi_hba_bus_config_port(self, (char *)arg,
8194 		    SE_BUSCONFIG)) != NULL) {
8195 			if (childp) {
8196 				ndi_hold_devi(child);
8197 				*childp = child;
8198 			}
8199 			ret = NDI_SUCCESS;
8200 		}
8201 		scsi_hba_devi_exit(self, circ);
8202 	} else
8203 		ret = ndi_busop_bus_config(self, flags, op, arg, childp, 0);
8204 
8205 out:
8206 #ifdef	DEBUG
8207 	if (ret != NDI_SUCCESS) {
8208 		if (scsi_hba_bus_config_failure_msg ||
8209 		    scsi_hba_bus_config_failure_dbg) {
8210 			scsi_hba_bus_config_failure_msg--;
8211 			printf("%s%d: bus_config_iportmap %p failure on %s: "
8212 			    "%d %d\n",
8213 			    ddi_driver_name(self), ddi_get_instance(self),
8214 			    (void *)iportmap,
8215 			    (op == BUS_CONFIG_ONE) ? (char *)arg : "ALL",
8216 			    (int)tsa, synced);
8217 		}
8218 		if (scsi_hba_bus_config_failure_dbg) {
8219 			scsi_hba_bus_config_failure_dbg--;
8220 			debug_enter("config_iportmap failure");
8221 		}
8222 	} else if (scsi_hba_bus_config_success_msg ||
8223 	    scsi_hba_bus_config_success_dbg) {
8224 		scsi_hba_bus_config_success_msg--;
8225 		printf("%s%d: bus_config_iportmap %p success on %s: %d %d\n",
8226 		    ddi_driver_name(self), ddi_get_instance(self),
8227 		    (void *)iportmap,
8228 		    (op == BUS_CONFIG_ONE) ? (char *)arg : "ALL",
8229 		    (int)tsa, synced);
8230 		if (scsi_hba_bus_config_success_dbg) {
8231 			scsi_hba_bus_config_success_dbg--;
8232 			debug_enter("config_iportmap success");
8233 		}
8234 	}
8235 #endif	/* DEBUG */
8236 	return (ret);
8237 }
8238 
8239 static int
8240 scsi_hba_bus_unconfig_iportmap(dev_info_t *self, uint_t flags,
8241     ddi_bus_config_op_t op, void *arg)
8242 {
8243 	flags &= ~NDI_DEVI_REMOVE;
8244 	return (ndi_busop_bus_unconfig(self, flags, op, arg));
8245 }
8246 
8247 /*
8248  * SCSI HBA bus config enumeration entry point. Called via the bus_ops
8249  * bus_config entry point for all SCSA HBA drivers.
8250  *
8251  *  o	If an HBA implements its own bus_config via tran_bus_config then we
8252  *	invoke it. An HBA that implements its own tran_bus_config entry	point
8253  *	may still call back into common SCSA code bus_config code for:
8254  *
8255  *	o SPI bus_config (scsi_hba_bus_spi)
8256  *	o LUN and secondary function enumeration (scsi_hba_enum_lsf_of_t()).
8257  *	o configuration of a specific device (scsi_device_config).
8258  *	o determining 1275 SCSI nodename and compatible property
8259  *	  (scsi_hba_nodename_compatible_get/_free).
8260  *
8261  *   o	Otherwise we implement a SCSI parallel interface (spi) bus config.
8262  *
8263  * Return NDI_SUCCESS if we might have created a new node.
8264  * Return NDI_FAILURE if we definitely did not create a new node.
8265  */
8266 static int
8267 scsi_hba_bus_config(dev_info_t *self, uint_t flags,
8268     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
8269 {
8270 	scsi_hba_tran_t	*tran;
8271 	int		ret;
8272 
8273 	/* make sure that we will not disappear */
8274 	ASSERT(DEVI(self)->devi_ref);
8275 
8276 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
8277 	if (tran == NULL) {
8278 		/* NULL tran driver.conf config (used by cmdk). */
8279 		if ((op == BUS_CONFIG_ONE) || (flags & NDI_DRV_CONF_REPROBE))
8280 			flags |= NDI_CONFIG_REPROBE;
8281 		return (ndi_busop_bus_config(self, flags, op, arg, childp, 0));
8282 	}
8283 
8284 	/* Check if self is HBA-only node. */
8285 	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
8286 		/* The bus_config request is to configure iports below HBA. */
8287 
8288 #ifdef	sparc
8289 		/*
8290 		 * Sparc's 'boot-device' OBP property value lacks an /iport@X/
8291 		 * component. Prior to the mount of root, we drive a disk@
8292 		 * BUS_CONFIG_ONE operatino down a level to resolve an
8293 		 * OBP 'boot-device' path.
8294 		 *
8295 		 * Future: Add (modrootloaded == 0) below, and insure that
8296 		 * all attempts bus_conf of 'bo_name' (in OBP form) occur
8297 		 * prior to 'modrootloaded = 1;' assignment in vfs_mountroot.
8298 		 */
8299 		if ((op == BUS_CONFIG_ONE) &&
8300 		    (strncmp((char *)arg, "disk@", strlen("disk@")) == 0)) {
8301 			return (scsi_hba_bus_config_prom_node(self,
8302 			    flags, arg, childp));
8303 		}
8304 #endif	/* sparc */
8305 
8306 		if (tran->tran_iportmap) {
8307 			/* config based on scsi_hba_iportmap API */
8308 			ret = scsi_hba_bus_config_iportmap(self,
8309 			    flags, op, arg, childp);
8310 		} else {
8311 			/* config based on 'iport_register' API */
8312 			ret = scsi_hba_bus_config_iports(self,
8313 			    flags, op, arg, childp);
8314 		}
8315 		return (ret);
8316 	}
8317 
8318 	/* Check to see how the iport/HBA does target/lun bus config. */
8319 	if (tran->tran_bus_config) {
8320 		/* HBA config based on Sun-private/legacy tran_bus_config */
8321 		ret = tran->tran_bus_config(self, flags, op, arg, childp);
8322 	} else if (tran->tran_tgtmap) {
8323 		/* SCSAv3 config based on scsi_hba_tgtmap_*() API */
8324 		ret =  scsi_hba_bus_config_tgtmap(self, flags, op, arg, childp);
8325 	} else {
8326 		/* SCSA config based on SCSI Parallel Interconnect */
8327 		ret = scsi_hba_bus_config_spi(self, flags, op, arg, childp);
8328 	}
8329 	return (ret);
8330 }
8331 
8332 /*
8333  * Called via the bus_ops bus_unconfig entry point for SCSI HBA drivers.
8334  */
8335 static int
8336 scsi_hba_bus_unconfig(dev_info_t *self, uint_t flags,
8337     ddi_bus_config_op_t op, void *arg)
8338 {
8339 	int		circ;
8340 	scsi_hba_tran_t	*tran;
8341 	int		ret;
8342 
8343 	tran = ddi_get_driver_private(self);
8344 	if (tran == NULL) {
8345 		/* NULL tran driver.conf unconfig (used by cmdk). */
8346 		return (ndi_busop_bus_unconfig(self, flags, op, arg));
8347 	}
8348 
8349 	/*
8350 	 * Purge barrier/probe node children. We do this prior to
8351 	 * tran_bus_unconfig in case the unconfig implementation calls back
8352 	 * into the common code at a different enumeration level, such a
8353 	 * scsi_device_config, which still creates barrier/probe nodes.
8354 	 */
8355 	scsi_hba_devi_enter(self, &circ);
8356 	scsi_hba_barrier_purge(self);
8357 	scsi_hba_devi_exit(self, circ);
8358 
8359 	/* Check if self is HBA-only node. */
8360 	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
8361 		/* The bus_config request is to unconfigure iports below HBA. */
8362 		if (tran->tran_iportmap) {
8363 			/* SCSAv3 unconfig based on scsi_hba_iportmap API */
8364 			ret = scsi_hba_bus_unconfig_iportmap(self,
8365 			    flags, op, arg);
8366 		} else if (tran->tran_bus_unconfig) {
8367 			/* HBA unconfig based on Sun-private/legacy API */
8368 			ret = tran->tran_bus_unconfig(self, flags, op, arg);
8369 		} else {
8370 			/* Standard framework unconfig. */
8371 			ret = ndi_busop_bus_unconfig(self, flags, op, arg);
8372 		}
8373 		return (ret);
8374 	}
8375 
8376 	/* Check to see how the iport/HBA does target/lun bus unconfig. */
8377 	if (tran->tran_bus_unconfig) {
8378 		/* HBA unconfig based on Sun-private/legacy tran_bus_unconfig */
8379 		ret = tran->tran_bus_unconfig(self, flags, op, arg);
8380 	} else if (tran->tran_tgtmap) {
8381 		/* SCSAv3 unconfig based on scsi_hba_tgtmap_*() API */
8382 		ret = scsi_hba_bus_unconfig_tgtmap(self, flags, op, arg);
8383 	} else {
8384 		/* SCSA unconfig based on SCSI Parallel Interconnect */
8385 		ret = scsi_hba_bus_unconfig_spi(self, flags, op, arg);
8386 	}
8387 	return (ret);
8388 }
8389 
8390 static int
8391 scsi_tgtmap_scsi_config(void *arg, damap_t *mapp, damap_id_t tgtid)
8392 {
8393 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
8394 	dev_info_t		*self = tran->tran_iport_dip;
8395 	impl_scsi_tgtmap_t	*tgtmap;
8396 	char			*tgtaddr;
8397 	int			cfg_status, mt;
8398 
8399 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
8400 	tgtaddr = damap_id2addr(mapp, tgtid);
8401 
8402 	if (scsi_lunmap_create(self, tgtmap, tgtaddr) != DDI_SUCCESS) {
8403 		SCSI_HBA_LOG((_LOG_NF(WARN),
8404 		    "failed to create lunmap for %s", tgtaddr));
8405 	}
8406 
8407 	mt = ddi_prop_get_int(DDI_DEV_T_ANY, self,
8408 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
8409 	    scsi_enumeration);
8410 	mt |= scsi_hba_log_mt_disable;
8411 
8412 	cfg_status = scsi_hba_bus_config_taddr(self, tgtaddr, mt, SE_HP);
8413 	if (cfg_status != NDI_SUCCESS) {
8414 		SCSI_HBA_LOG((_LOGCFG, self, NULL, "%s @%s config status %d",
8415 		    damap_name(mapp), tgtaddr, cfg_status));
8416 		scsi_lunmap_destroy(self, tgtmap, tgtaddr);
8417 		return (DAM_FAILURE);
8418 	}
8419 
8420 	return (DAM_SUCCESS);
8421 }
8422 
8423 
8424 static int
8425 scsi_tgtmap_scsi_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
8426 {
8427 	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
8428 	dev_info_t		*self = tran->tran_iport_dip;
8429 	impl_scsi_tgtmap_t	*tgtmap;
8430 	char			*tgt_addr;
8431 
8432 	tgtmap = (impl_scsi_tgtmap_t *)tran->tran_tgtmap;
8433 	tgt_addr = damap_id2addr(mapp, tgtid);
8434 
8435 	SCSI_HBA_LOG((_LOGUNCFG, self, NULL, "%s @%s", damap_name(mapp),
8436 	    tgt_addr));
8437 	scsi_lunmap_destroy(self, tgtmap, tgt_addr);
8438 	return (DAM_SUCCESS);
8439 }
8440 
8441 static int
8442 scsi_tgtmap_smp_config(void *arg, damap_t *mapp, damap_id_t tgtid)
8443 {
8444 	scsi_hba_tran_t	*tran = (scsi_hba_tran_t *)arg;
8445 	dev_info_t	*self = tran->tran_iport_dip;
8446 	char		*addr;
8447 
8448 	addr = damap_id2addr(mapp, tgtid);
8449 	SCSI_HBA_LOG((_LOGCFG, self, NULL, "%s @%s", damap_name(mapp), addr));
8450 
8451 	return ((smp_hba_bus_config_taddr(self, addr) == NDI_SUCCESS) ?
8452 	    DAM_SUCCESS : DAM_FAILURE);
8453 }
8454 
8455 static int
8456 scsi_tgtmap_smp_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
8457 {
8458 	scsi_hba_tran_t	*tran = (scsi_hba_tran_t *)arg;
8459 	dev_info_t	*self = tran->tran_iport_dip;
8460 	char		*addr;
8461 	dev_info_t	*child;
8462 	char		nameaddr[SCSI_MAXNAMELEN];
8463 	int		circ;
8464 
8465 	addr = damap_id2addr(mapp, tgtid);
8466 	SCSI_HBA_LOG((_LOGUNCFG, self, NULL, "%s @%s", damap_name(mapp), addr));
8467 
8468 	(void) snprintf(nameaddr, sizeof (nameaddr), "smp@%s", addr);
8469 	scsi_hba_devi_enter(self, &circ);
8470 	if ((child = ndi_devi_findchild(self, nameaddr)) == NULL) {
8471 		scsi_hba_devi_exit(self, circ);
8472 		return (DAM_SUCCESS);
8473 	}
8474 
8475 	if (ndi_devi_offline(child,
8476 	    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) == DDI_SUCCESS) {
8477 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
8478 		    "devinfo smp@%s offlined and removed", addr));
8479 	} else if (ndi_devi_device_remove(child)) {
8480 		/* Offline/remove failed, note new device_remove */
8481 		SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
8482 		    "devinfo smp@%s offline failed, device_remove",
8483 		    addr));
8484 	}
8485 	scsi_hba_devi_exit(self, circ);
8486 	return (DAM_SUCCESS);
8487 }
8488 
8489 /* ARGSUSED1 */
8490 static void
8491 scsi_tgtmap_smp_activate(void *map_priv, char *tgt_addr, int addrid,
8492     void **tgt_privp)
8493 {
8494 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8495 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8496 
8497 	if (tgtmap->tgtmap_activate_cb) {
8498 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s activated",
8499 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE]),
8500 		    tgt_addr));
8501 
8502 		(*tgtmap->tgtmap_activate_cb)(tgtmap->tgtmap_mappriv,
8503 		    tgt_addr, SCSI_TGT_SMP_DEVICE, tgt_privp);
8504 	}
8505 }
8506 
8507 /* ARGSUSED1 */
8508 static void
8509 scsi_tgtmap_smp_deactivate(void *map_priv, char *tgt_addr, int addrid,
8510     void *tgt_privp, damap_deact_rsn_t damap_rsn)
8511 {
8512 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8513 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8514 	boolean_t		tgtmap_rereport;
8515 	scsi_tgtmap_deact_rsn_t	tgtmap_rsn;
8516 
8517 	if (tgtmap->tgtmap_deactivate_cb) {
8518 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s deactivated %d",
8519 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE]),
8520 		    tgt_addr, damap_rsn));
8521 
8522 		if (damap_rsn == DAMAP_DEACT_RSN_GONE)
8523 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_GONE;
8524 		else if (damap_rsn == DAMAP_DEACT_RSN_CFG_FAIL)
8525 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_CFG_FAIL;
8526 		else if (damap_rsn == DAMAP_DEACT_RSN_UNSTBL)
8527 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_UNSTBL;
8528 		else {
8529 			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
8530 			    "%s @%s deactivated with unknown rsn",
8531 			    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE]),
8532 			    tgt_addr));
8533 			return;
8534 		}
8535 
8536 		tgtmap_rereport = (*tgtmap->tgtmap_deactivate_cb)
8537 		    (tgtmap->tgtmap_mappriv, tgt_addr,
8538 		    SCSI_TGT_SMP_DEVICE, tgt_privp, tgtmap_rsn);
8539 
8540 		if ((tgtmap_rsn == SCSI_TGT_DEACT_RSN_CFG_FAIL) &&
8541 		    (tgtmap_rereport == B_FALSE)) {
8542 			SCSI_HBA_LOG((_LOG(WARN), NULL, self,
8543 			    "%s enumeration failed, no more retries until "
8544 			    "config change occurs", tgt_addr));
8545 		}
8546 	}
8547 }
8548 
8549 /* ARGSUSED1 */
8550 static void
8551 scsi_tgtmap_scsi_activate(void *map_priv, char *tgt_addr, int addrid,
8552     void **tgt_privp)
8553 {
8554 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8555 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8556 
8557 	if (tgtmap->tgtmap_activate_cb) {
8558 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s activated",
8559 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]),
8560 		    tgt_addr));
8561 
8562 		(*tgtmap->tgtmap_activate_cb)(tgtmap->tgtmap_mappriv,
8563 		    tgt_addr, SCSI_TGT_SCSI_DEVICE, tgt_privp);
8564 	}
8565 }
8566 
8567 /* ARGSUSED1 */
8568 static void
8569 scsi_tgtmap_scsi_deactivate(void *map_priv, char *tgt_addr, int addrid,
8570     void *tgt_privp, damap_deact_rsn_t damap_rsn)
8571 {
8572 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)map_priv;
8573 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8574 	boolean_t		tgtmap_rereport;
8575 	scsi_tgtmap_deact_rsn_t	tgtmap_rsn;
8576 
8577 	if (tgtmap->tgtmap_deactivate_cb) {
8578 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s @%s deactivated %d",
8579 		    damap_name(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]),
8580 		    tgt_addr, damap_rsn));
8581 
8582 		if (damap_rsn == DAMAP_DEACT_RSN_GONE)
8583 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_GONE;
8584 		else if (damap_rsn == DAMAP_DEACT_RSN_CFG_FAIL)
8585 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_CFG_FAIL;
8586 		else if (damap_rsn == DAMAP_DEACT_RSN_UNSTBL)
8587 			tgtmap_rsn = SCSI_TGT_DEACT_RSN_UNSTBL;
8588 		else {
8589 			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
8590 			    "%s @%s deactivated with unknown rsn", damap_name(
8591 			    tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]),
8592 			    tgt_addr));
8593 			return;
8594 		}
8595 
8596 		tgtmap_rereport = (*tgtmap->tgtmap_deactivate_cb)
8597 		    (tgtmap->tgtmap_mappriv, tgt_addr,
8598 		    SCSI_TGT_SCSI_DEVICE, tgt_privp, tgtmap_rsn);
8599 
8600 		if ((tgtmap_rsn == SCSI_TGT_DEACT_RSN_CFG_FAIL) &&
8601 		    (tgtmap_rereport == B_FALSE)) {
8602 			SCSI_HBA_LOG((_LOG(WARN), NULL, self,
8603 			    "%s enumeration failed, no more retries until "
8604 			    "config change occurs", tgt_addr));
8605 		}
8606 	}
8607 }
8608 
8609 
8610 int
8611 scsi_hba_tgtmap_create(dev_info_t *self, scsi_tgtmap_mode_t mode,
8612     int csync_usec, int settle_usec, void *tgtmap_priv,
8613     scsi_tgt_activate_cb_t activate_cb, scsi_tgt_deactivate_cb_t deactivate_cb,
8614     scsi_hba_tgtmap_t **handle)
8615 {
8616 	scsi_hba_tran_t		*tran;
8617 	damap_t			*mapp;
8618 	char			context[64];
8619 	impl_scsi_tgtmap_t	*tgtmap;
8620 	damap_rptmode_t		rpt_style;
8621 	char			*scsi_binding_set;
8622 	int			optflags;
8623 
8624 	if (self == NULL || csync_usec == 0 ||
8625 	    settle_usec == 0 || handle == NULL)
8626 		return (DDI_FAILURE);
8627 
8628 	*handle = NULL;
8629 
8630 	if (scsi_hba_iport_unit_address(self) == NULL)
8631 		return (DDI_FAILURE);
8632 
8633 	switch (mode) {
8634 	case SCSI_TM_FULLSET:
8635 		rpt_style = DAMAP_REPORT_FULLSET;
8636 		break;
8637 	case SCSI_TM_PERADDR:
8638 		rpt_style = DAMAP_REPORT_PERADDR;
8639 		break;
8640 	default:
8641 		return (DDI_FAILURE);
8642 	}
8643 
8644 	tran = (scsi_hba_tran_t *)ddi_get_driver_private(self);
8645 	ASSERT(tran);
8646 	if (tran == NULL)
8647 		return (DDI_FAILURE);
8648 
8649 	tgtmap = kmem_zalloc(sizeof (*tgtmap), KM_SLEEP);
8650 	tgtmap->tgtmap_tran = tran;
8651 	tgtmap->tgtmap_activate_cb = activate_cb;
8652 	tgtmap->tgtmap_deactivate_cb = deactivate_cb;
8653 	tgtmap->tgtmap_mappriv = tgtmap_priv;
8654 
8655 	tgtmap->tgtmap_create_window = 1;	/* start with window */
8656 	tgtmap->tgtmap_create_time = ddi_get_lbolt64();
8657 	tgtmap->tgtmap_create_csync_usec = csync_usec;
8658 	tgtmap->tgtmap_settle_usec = settle_usec;
8659 	tgtmap->tgtmap_sync_cnt = 0;
8660 
8661 	optflags = (ddi_prop_get_int(DDI_DEV_T_ANY, self,
8662 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
8663 	    scsi_enumeration) & SCSI_ENUMERATION_MT_TARGET_DISABLE) ?
8664 	    DAMAP_SERIALCONFIG : DAMAP_MTCONFIG;
8665 
8666 	(void) snprintf(context, sizeof (context), "%s%d.tgtmap.scsi",
8667 	    ddi_driver_name(self), ddi_get_instance(self));
8668 	SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8669 	if (damap_create(context, rpt_style, optflags, settle_usec,
8670 	    tgtmap, scsi_tgtmap_scsi_activate, scsi_tgtmap_scsi_deactivate,
8671 	    tran, scsi_tgtmap_scsi_config, scsi_tgtmap_scsi_unconfig,
8672 	    &mapp) != DAM_SUCCESS) {
8673 		kmem_free(tgtmap, sizeof (*tgtmap));
8674 		return (DDI_FAILURE);
8675 	}
8676 	tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE] = mapp;
8677 
8678 	(void) snprintf(context, sizeof (context), "%s%d.tgtmap.smp",
8679 	    ddi_driver_name(self), ddi_get_instance(self));
8680 	SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8681 	if (damap_create(context, rpt_style, optflags,
8682 	    settle_usec, tgtmap, scsi_tgtmap_smp_activate,
8683 	    scsi_tgtmap_smp_deactivate,
8684 	    tran, scsi_tgtmap_smp_config, scsi_tgtmap_smp_unconfig,
8685 	    &mapp) != DAM_SUCCESS) {
8686 		damap_destroy(tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE]);
8687 		kmem_free(tgtmap, sizeof (*tgtmap));
8688 		return (DDI_FAILURE);
8689 	}
8690 	tgtmap->tgtmap_dam[SCSI_TGT_SMP_DEVICE] = mapp;
8691 
8692 	tran->tran_tgtmap = (scsi_hba_tgtmap_t *)tgtmap;
8693 	*handle = (scsi_hba_tgtmap_t *)tgtmap;
8694 
8695 	/*
8696 	 * We have now set tran_tgtmap, marking the tran as using tgtmap
8697 	 * enumeration services.  To prevent the generation of legacy spi
8698 	 * 'binding-set' compatible forms, remove the 'scsi-binding-set'
8699 	 * property.
8700 	 */
8701 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
8702 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-binding-set",
8703 	    &scsi_binding_set) == DDI_PROP_SUCCESS) {
8704 		if (strcmp(scsi_binding_set, scsi_binding_set_spi) == 0)
8705 			(void) ndi_prop_remove(DDI_DEV_T_NONE, self,
8706 			    "scsi-binding-set");
8707 		ddi_prop_free(scsi_binding_set);
8708 	}
8709 	return (DDI_SUCCESS);
8710 }
8711 
8712 void
8713 scsi_hba_tgtmap_destroy(scsi_hba_tgtmap_t *handle)
8714 {
8715 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8716 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8717 	int			i;
8718 
8719 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8720 		if (tgtmap->tgtmap_dam[i]) {
8721 			SCSI_HBA_LOG((_LOGTGT, self, NULL,
8722 			    "%s", damap_name(tgtmap->tgtmap_dam[i])));
8723 			damap_destroy(tgtmap->tgtmap_dam[i]);
8724 		}
8725 	}
8726 	kmem_free(tgtmap, sizeof (*tgtmap));
8727 }
8728 
8729 /* return 1 if all maps ended up syned */
8730 static int
8731 scsi_tgtmap_sync(scsi_hba_tgtmap_t *handle, int sync_usec)
8732 {
8733 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8734 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8735 	int			all_synced = 1;
8736 	int			synced;
8737 	int			i;
8738 
8739 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8740 		if (tgtmap->tgtmap_dam[i]) {
8741 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s sync begin",
8742 			    damap_name(tgtmap->tgtmap_dam[i])));
8743 			synced = damap_sync(tgtmap->tgtmap_dam[i], sync_usec);
8744 			all_synced &= synced;
8745 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s sync end %d",
8746 			    damap_name(tgtmap->tgtmap_dam[i]), synced));
8747 
8748 		}
8749 	}
8750 	return (all_synced);
8751 }
8752 
8753 /* return 1 if all maps ended up empty */
8754 static int
8755 scsi_tgtmap_is_empty(scsi_hba_tgtmap_t *handle)
8756 {
8757 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8758 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8759 	int			all_empty = 1;
8760 	int			empty;
8761 	int			i;
8762 
8763 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8764 		if (tgtmap->tgtmap_dam[i]) {
8765 			empty = damap_is_empty(tgtmap->tgtmap_dam[i]);
8766 			all_empty &= empty;
8767 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s is_empty %d",
8768 			    damap_name(tgtmap->tgtmap_dam[i]), empty));
8769 		}
8770 	}
8771 
8772 	return (all_empty);
8773 }
8774 
8775 static int
8776 scsi_tgtmap_beginf(scsi_hba_tgtmap_t *handle, boolean_t do_begin)
8777 {
8778 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8779 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8780 	char			*context;
8781 	int			rv = DAM_SUCCESS;
8782 	int			i;
8783 
8784 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8785 		if (tgtmap->tgtmap_dam[i] == NULL) {
8786 			continue;
8787 		}
8788 
8789 		context = damap_name(tgtmap->tgtmap_dam[i]);
8790 		if (do_begin == B_TRUE) {
8791 			if (i == SCSI_TGT_SCSI_DEVICE) {
8792 				/*
8793 				 * In scsi_device context, so we have the
8794 				 * 'context' string, diagnose the case where
8795 				 * the tgtmap caller is failing to make
8796 				 * forward progress, i.e. the caller is never
8797 				 * completing an observation by calling
8798 				 * scsi_hbg_tgtmap_set_end. If this occurs,
8799 				 * the solaris target/lun state may be out
8800 				 * of sync with hardware.
8801 				 */
8802 				if (tgtmap->tgtmap_reports++ >=
8803 				    scsi_hba_tgtmap_reports_max) {
8804 					tgtmap->tgtmap_noisy++;
8805 					if (tgtmap->tgtmap_noisy == 1) {
8806 						SCSI_HBA_LOG((_LOG(WARN),
8807 						    self, NULL,
8808 						    "%s: failing tgtmap begin",
8809 						    context));
8810 					}
8811 				}
8812 			}
8813 
8814 			rv = damap_addrset_begin(tgtmap->tgtmap_dam[i]);
8815 		} else {
8816 			rv = damap_addrset_flush(tgtmap->tgtmap_dam[i]);
8817 		}
8818 
8819 		if (rv != DAM_SUCCESS) {
8820 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s FAIL", context));
8821 		} else {
8822 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8823 		}
8824 	}
8825 
8826 	return ((rv == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8827 }
8828 
8829 
8830 int
8831 scsi_hba_tgtmap_set_begin(scsi_hba_tgtmap_t *handle)
8832 {
8833 	return (scsi_tgtmap_beginf(handle, B_TRUE));
8834 }
8835 
8836 int
8837 scsi_hba_tgtmap_set_flush(scsi_hba_tgtmap_t *handle)
8838 {
8839 	return (scsi_tgtmap_beginf(handle, B_FALSE));
8840 }
8841 
8842 int
8843 scsi_hba_tgtmap_set_add(scsi_hba_tgtmap_t *handle,
8844     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr, void *tgt_priv)
8845 {
8846 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8847 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8848 
8849 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8850 		return (DDI_FAILURE);
8851 
8852 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8853 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8854 
8855 	return ((damap_addrset_add(tgtmap->tgtmap_dam[tgt_type], tgt_addr,
8856 	    NULL, NULL, tgt_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8857 }
8858 
8859 /*ARGSUSED*/
8860 int
8861 scsi_hba_tgtmap_set_end(scsi_hba_tgtmap_t *handle, uint_t flags)
8862 {
8863 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8864 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8865 	char			*context;
8866 	int			rv = DDI_SUCCESS;
8867 	int			i;
8868 
8869 	tgtmap->tgtmap_reports = tgtmap->tgtmap_noisy = 0;
8870 
8871 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8872 		if (tgtmap->tgtmap_dam[i] == NULL)
8873 			continue;
8874 		context = damap_name(tgtmap->tgtmap_dam[i]);
8875 		if (damap_addrset_end(
8876 		    tgtmap->tgtmap_dam[i], 0) != DAM_SUCCESS) {
8877 			SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s FAIL", context));
8878 			rv = DDI_FAILURE;
8879 			continue;
8880 		}
8881 
8882 		SCSI_HBA_LOG((_LOGTGT, self, NULL, "%s", context));
8883 	}
8884 	return (rv);
8885 }
8886 
8887 int
8888 scsi_hba_tgtmap_tgt_add(scsi_hba_tgtmap_t *handle,
8889     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr, void *tgt_priv)
8890 
8891 {
8892 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8893 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8894 
8895 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8896 		return (DDI_FAILURE);
8897 
8898 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8899 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8900 
8901 	return ((damap_addr_add(tgtmap->tgtmap_dam[tgt_type], tgt_addr, NULL,
8902 	    NULL, tgt_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8903 }
8904 
8905 int
8906 scsi_hba_tgtmap_tgt_remove(scsi_hba_tgtmap_t *handle,
8907     scsi_tgtmap_tgt_type_t tgt_type, char *tgt_addr)
8908 {
8909 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8910 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8911 
8912 	if (tgt_type >= SCSI_TGT_NTYPES || !tgtmap->tgtmap_dam[tgt_type])
8913 		return (DDI_FAILURE);
8914 
8915 	SCSI_HBA_LOG((_LOGTGT, self, NULL,
8916 	    "%s @%s", damap_name(tgtmap->tgtmap_dam[tgt_type]), tgt_addr));
8917 
8918 	return ((damap_addr_del(tgtmap->tgtmap_dam[tgt_type],
8919 	    tgt_addr) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
8920 }
8921 
8922 int
8923 scsi_hba_tgtmap_lookup(scsi_hba_tgtmap_t *handle,
8924     char *tgt_addr, scsi_tgtmap_tgt_type_t *r_type)
8925 {
8926 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)handle;
8927 	dev_info_t		*self = tgtmap->tgtmap_tran->tran_iport_dip;
8928 	damap_id_t		tgtid;
8929 	int			i;
8930 
8931 	for (i = 0; i < SCSI_TGT_NTYPES; i++) {
8932 		tgtid = damap_lookup(tgtmap->tgtmap_dam[i], tgt_addr);
8933 		if (tgtid != NODAM) {
8934 			*r_type = i;
8935 			SCSI_HBA_LOG((_LOG(3), self, NULL,
8936 			    "%s @%s found: type %d",
8937 			    damap_name(tgtmap->tgtmap_dam[i]), tgt_addr, i));
8938 			damap_id_rele(tgtmap->tgtmap_dam[i], tgtid);
8939 			return (DDI_SUCCESS);
8940 		}
8941 	}
8942 
8943 	SCSI_HBA_LOG((_LOG(3), self, NULL,
8944 	    "%s%d.tgtmap @%s not found",
8945 	    ddi_driver_name(self), ddi_get_instance(self), tgt_addr));
8946 	return (DDI_FAILURE);
8947 }
8948 
8949 /*
8950  * Return the unit-address of an 'iport' node, or NULL for non-iport node.
8951  */
8952 char *
8953 scsi_hba_iport_unit_address(dev_info_t *self)
8954 {
8955 	/*
8956 	 * NOTE: Since 'self' could be a SCSA iport node or a SCSA HBA node,
8957 	 * we can't use SCSA flavors: the flavor of a SCSA HBA node is not
8958 	 * established/owned by SCSA, it is established by the nexus that
8959 	 * created the SCSA HBA node (PCI) as a child.
8960 	 *
8961 	 * NOTE: If we want to support a node_name other than "iport" for
8962 	 * an iport node then we can add support for a "scsa-iport-node-name"
8963 	 * property on the SCSA HBA node.  A SCSA HBA driver would set this
8964 	 * property on the SCSA HBA node prior to using the iport API.
8965 	 */
8966 	if (strcmp(ddi_node_name(self), "iport") == 0)
8967 		return (ddi_get_name_addr(self));
8968 	else
8969 		return (NULL);
8970 }
8971 
8972 /*
8973  * Define a SCSI initiator port (bus/channel) for an HBA card that needs to
8974  * support multiple SCSI ports, but only has a single HBA devinfo node. This
8975  * function should be called from the HBA's attach(9E) implementation (when
8976  * processing the HBA devinfo node attach) after the number of SCSI ports on
8977  * the card is known or when the HBA driver DR handler detects a new port.
8978  * The function returns 0 on failure and 1 on success.
8979  *
8980  * The implementation will add the port value into the "scsi-iports" property
8981  * value maintained on the HBA node as. These properties are used by the generic
8982  * scsi bus_config implementation to dynamicaly enumerate the specified iport
8983  * children. The enumeration code will, on demand, create the appropriate
8984  * iport children with a SCSI_ADDR_PROP_IPORTUA unit address. This node will
8985  * bind to the same driver as the HBA node itself. This means that an HBA
8986  * driver that uses iports should expect probe(9E), attach(9E), and detach(9E)
8987  * calls on the iport children of the HBA.  If configuration for all ports was
8988  * already done during HBA node attach, the driver should just return
8989  * DDI_SUCCESS when confronted with an iport node.
8990  *
8991  * A maximum of 32 iport ports are supported per HBA devinfo node.
8992  *
8993  * A NULL "port" can be used to indicate that the framework should enumerate
8994  * target children on the HBA node itself, in addition to enumerating target
8995  * children on any iport nodes declared. There are two reasons that an HBA may
8996  * wish to have target children enumerated on both the HBA node and iport
8997  * node(s):
8998  *
8999  *   o  If, in the past, HBA hardware had only a single physical port but now
9000  *      supports multiple physical ports, the updated driver that supports
9001  *      multiple physical ports may want to avoid /devices path upgrade issues
9002  *      by enumerating the first physical port under the HBA instead of as a
9003  *      iport.
9004  *
9005  *   o  Some hardware RAID HBA controllers (mlx, chs, etc) support multiple
9006  *      SCSI physical ports configured so that various physical devices on
9007  *      the physical ports are amalgamated into virtual devices on a virtual
9008  *      port.  Amalgamated physical devices no longer appear to the host OS
9009  *      on the physical ports, but other non-amalgamated devices may still be
9010  *      visible on the physical ports.  These drivers use a model where the
9011  *      physical ports are iport nodes and the HBA node is the virtual port to
9012  *      the configured virtual devices.
9013  */
9014 int
9015 scsi_hba_iport_register(dev_info_t *self, char *port)
9016 {
9017 	unsigned int ports = 0;
9018 	int rval, i;
9019 	char **iports, **newiports;
9020 
9021 	ASSERT(self);
9022 	if (self == NULL)
9023 		return (DDI_FAILURE);
9024 
9025 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
9026 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
9027 	    &ports);
9028 
9029 	if (ports >= SCSI_HBA_MAX_IPORTS) {
9030 		ddi_prop_free(iports);
9031 		return (DDI_FAILURE);
9032 	}
9033 
9034 	if (rval == DDI_PROP_SUCCESS) {
9035 		for (i = 0; i < ports; i++) {
9036 			if (strcmp(port, iports[i]) == 0) {
9037 				/* iport already registered */
9038 				ddi_prop_free(iports);
9039 				return (DDI_SUCCESS);
9040 			}
9041 		}
9042 	}
9043 
9044 	newiports = kmem_alloc((sizeof (char *) * (ports + 1)), KM_SLEEP);
9045 
9046 	for (i = 0; i < ports; i++) {
9047 		newiports[i] = strdup(iports[i]);
9048 	}
9049 	newiports[ports] = strdup(port);
9050 	ports++;
9051 
9052 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, self,
9053 	    "scsi-iports", newiports, ports) != DDI_PROP_SUCCESS) {
9054 		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
9055 		    "failed to establish %s %s",
9056 		    SCSI_ADDR_PROP_IPORTUA, port));
9057 		rval = DDI_FAILURE;
9058 	} else {
9059 		rval = DDI_SUCCESS;
9060 	}
9061 
9062 	/* If there is iport exist, free property */
9063 	if (ports > 1)
9064 		ddi_prop_free(iports);
9065 	for (i = 0; i < ports; i++) {
9066 		strfree(newiports[i]);
9067 	}
9068 	kmem_free(newiports, (sizeof (char *)) * ports);
9069 
9070 	return (rval);
9071 }
9072 
9073 /*
9074  * Check if the HBA has any scsi_hba_iport_register()ed children.
9075  */
9076 int
9077 scsi_hba_iport_exist(dev_info_t *self)
9078 {
9079 	unsigned int ports = 0;
9080 	char **iports;
9081 	int rval;
9082 
9083 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
9084 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
9085 	    &ports);
9086 
9087 	if (rval != DDI_PROP_SUCCESS)
9088 		return (0);
9089 
9090 	/* If there is now at least 1 iport, then iports is valid */
9091 	if (ports > 0) {
9092 		rval = 1;
9093 	} else
9094 		rval = 0;
9095 	ddi_prop_free(iports);
9096 
9097 	return (rval);
9098 }
9099 
9100 dev_info_t *
9101 scsi_hba_iport_find(dev_info_t *self, char *portnm)
9102 {
9103 	char		*addr = NULL;
9104 	char		**iports;
9105 	unsigned int	num_iports = 0;
9106 	int		rval = DDI_FAILURE;
9107 	int		i = 0;
9108 	dev_info_t	*child = NULL;
9109 
9110 	/* check to see if this is an HBA that defined scsi iports */
9111 	rval = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
9112 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
9113 	    &num_iports);
9114 
9115 	if (rval != DDI_SUCCESS) {
9116 		return (NULL);
9117 	}
9118 	ASSERT(num_iports > 0);
9119 
9120 	/* check to see if this port was registered */
9121 	for (i = 0; i < num_iports; i++) {
9122 		if (strcmp(iports[i], portnm) == 0)
9123 			break;
9124 	}
9125 
9126 	if (i == num_iports) {
9127 		child = NULL;
9128 		goto out;
9129 	}
9130 
9131 	addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
9132 	(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s", portnm);
9133 	rval = ndi_devi_config_one(self, addr, &child, NDI_NO_EVENT);
9134 	kmem_free(addr, SCSI_MAXNAMELEN);
9135 
9136 	if (rval != DDI_SUCCESS) {
9137 		child = NULL;
9138 	}
9139 out:
9140 	ddi_prop_free(iports);
9141 	return (child);
9142 }
9143 
9144 /*
9145  * Search/create the specified iport node
9146  */
9147 static dev_info_t *
9148 scsi_hba_bus_config_port(dev_info_t *self, char *nameaddr, scsi_enum_t se)
9149 {
9150 	dev_info_t	*child;		/* iport child of HBA node */
9151 	scsi_hba_tran_t	*tran;
9152 	char		*addr;
9153 	char		*compat;
9154 
9155 	/*
9156 	 * See if the iport node already exists.
9157 	 */
9158 	addr = nameaddr + strlen("iport@");
9159 	if (child = ndi_devi_findchild(self, nameaddr)) {
9160 		if (ndi_devi_device_isremoved(child)) {
9161 			if ((se == SE_HP) || !ndi_dev_is_hotplug_node(child)) {
9162 				if (ndi_devi_device_insert(child))
9163 					SCSI_HBA_LOG((_LOGCFG, self, NULL,
9164 					    "devinfo iport@%s device_reinsert",
9165 					    addr));
9166 			} else
9167 				return (NULL);
9168 		}
9169 		return (child);
9170 	}
9171 
9172 
9173 	/*
9174 	 * If config based on scsi_hba_iportmap API, only allow create
9175 	 * from hotplug.
9176 	 */
9177 	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
9178 	ASSERT(tran);
9179 	if (tran->tran_iportmap && (se != SE_HP))
9180 		return (NULL);
9181 
9182 	/* allocate and initialize a new "iport" node */
9183 	ndi_devi_alloc_sleep(self, "iport",
9184 	    (se == SE_HP) ? DEVI_SID_HP_NODEID : DEVI_SID_NODEID,
9185 	    &child);
9186 	ASSERT(child);
9187 	/*
9188 	 * Set the flavor of the child to be IPORT flavored
9189 	 */
9190 	ndi_flavor_set(child, SCSA_FLAVOR_IPORT);
9191 
9192 	/*
9193 	 * Add the SCSI_ADDR_PROP_IPORTUA addressing property for this child.
9194 	 * This property is used to identify a iport node, and to represent the
9195 	 * nodes @addr form via node properties.
9196 	 *
9197 	 * Add "compatible" property to the "scsi-iport" node to cause it bind
9198 	 * to the same driver as the HBA  driver. Use the "driver" name
9199 	 * instead of the "binding name" to distinguish from hw node.
9200 	 *
9201 	 * Give the HBA a chance, via tran_set_name_prop, to set additional
9202 	 * iport node properties or to change the "compatible" binding
9203 	 * prior to init_child.
9204 	 *
9205 	 * NOTE: the order of these operations is important so that
9206 	 * scsi_hba_iport works when called.
9207 	 */
9208 	compat = (char *)ddi_driver_name(self);
9209 	if ((ndi_prop_update_string(DDI_DEV_T_NONE, child,
9210 	    SCSI_ADDR_PROP_IPORTUA, addr) != DDI_PROP_SUCCESS) ||
9211 	    (ndi_prop_update_string_array(DDI_DEV_T_NONE, child,
9212 	    "compatible", &compat, 1) != DDI_PROP_SUCCESS) ||
9213 	    ddi_pathname_obp_set(child, NULL) != DDI_SUCCESS) {
9214 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s failed dynamic decoration",
9215 		    nameaddr));
9216 		(void) ddi_remove_child(child, 0);
9217 		child = NULL;
9218 	} else {
9219 		/*
9220 		 * Online/attach in order to get events so devfsadm will
9221 		 * create public names.
9222 		 */
9223 		ndi_hold_devi(child);
9224 		if (ndi_devi_online(child, 0) != NDI_SUCCESS) {
9225 			ndi_rele_devi(child);
9226 			ndi_prop_remove_all(child);
9227 			(void) ndi_devi_free(child);
9228 			child = NULL;
9229 		} else
9230 			ndi_rele_devi(child);
9231 	}
9232 
9233 	return (child);
9234 }
9235 
9236 #ifdef	sparc
9237 /*
9238  * Future: When iportmap boot support is added, consider rewriting this to
9239  * perform a scsi_hba_bus_config(BUS_CONFIG_ALL) on self (HBA) followed by
9240  * a scsi_hba_bus_config(BUS_CONFIG_ONE) on each child of self (each iport).
9241  */
9242 /* ARGSUSED */
9243 static int
9244 scsi_hba_bus_config_prom_node(dev_info_t *self, uint_t flags,
9245     void *arg, dev_info_t **childp)
9246 {
9247 	char		**iports;
9248 	int		circ, i;
9249 	int		ret = NDI_FAILURE;
9250 	unsigned int	num_iports = 0;
9251 	dev_info_t	*pdip = NULL;
9252 	char		*addr = NULL;
9253 
9254 	/* check to see if this is an HBA that defined scsi iports */
9255 	ret = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
9256 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
9257 	    &num_iports);
9258 
9259 	if (ret != DDI_SUCCESS) {
9260 		return (ret);
9261 	}
9262 
9263 	ASSERT(num_iports > 0);
9264 
9265 	addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
9266 
9267 	ret = NDI_FAILURE;
9268 
9269 	scsi_hba_devi_enter(self, &circ);
9270 
9271 	/* create iport nodes for each scsi port/bus */
9272 	for (i = 0; i < num_iports; i++) {
9273 		bzero(addr, SCSI_MAXNAMELEN);
9274 		/* Prepend the iport name */
9275 		(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s",
9276 		    iports[i]);
9277 		if (pdip = scsi_hba_bus_config_port(self, addr, SE_BUSCONFIG)) {
9278 			if (ndi_busop_bus_config(self, NDI_NO_EVENT,
9279 			    BUS_CONFIG_ONE, addr, &pdip, 0) !=
9280 			    NDI_SUCCESS) {
9281 				continue;
9282 			}
9283 			/*
9284 			 * Try to configure child under iport see wehter
9285 			 * request node is the child of the iport node
9286 			 */
9287 			if (ndi_devi_config_one(pdip, arg, childp,
9288 			    NDI_NO_EVENT) == NDI_SUCCESS) {
9289 				ret = NDI_SUCCESS;
9290 				break;
9291 			}
9292 		}
9293 	}
9294 
9295 	scsi_hba_devi_exit(self, circ);
9296 
9297 	kmem_free(addr, SCSI_MAXNAMELEN);
9298 
9299 	ddi_prop_free(iports);
9300 
9301 	return (ret);
9302 }
9303 #endif
9304 
9305 /*
9306  * Perform iport port/bus bus_config.
9307  */
9308 static int
9309 scsi_hba_bus_config_iports(dev_info_t *self, uint_t flags,
9310     ddi_bus_config_op_t op, void *arg, dev_info_t **childp)
9311 {
9312 	char		*nameaddr, *addr;
9313 	char		**iports;
9314 	int		circ, i;
9315 	int		ret = NDI_FAILURE;
9316 	unsigned int	num_iports = 0;
9317 
9318 	/* check to see if this is an HBA that defined scsi iports */
9319 	ret = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, self,
9320 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-iports", &iports,
9321 	    &num_iports);
9322 
9323 	if (ret != DDI_SUCCESS) {
9324 		return (ret);
9325 	}
9326 
9327 	ASSERT(num_iports > 0);
9328 
9329 	scsi_hba_devi_enter(self, &circ);
9330 
9331 	switch (op) {
9332 	case BUS_CONFIG_ONE:
9333 		/* return if this operation is not against an iport node */
9334 		nameaddr = (char *)arg;
9335 		if ((nameaddr == NULL) ||
9336 		    (strncmp(nameaddr, "iport@", strlen("iport@")) != 0)) {
9337 			ret = NDI_FAILURE;
9338 			scsi_hba_devi_exit(self, circ);
9339 			ddi_prop_free(iports);
9340 			return (ret);
9341 		}
9342 
9343 		/* parse the port number from "iport@%s" */
9344 		addr = nameaddr + strlen("iport@");
9345 
9346 		/* check to see if this port was registered */
9347 		for (i = 0; i < num_iports; i++) {
9348 			if (strcmp((iports[i]), addr) == 0)
9349 				break;
9350 		}
9351 
9352 		if (i == num_iports) {
9353 			ret = NDI_FAILURE;
9354 			break;
9355 		}
9356 
9357 		/* create the iport node child */
9358 		if (scsi_hba_bus_config_port(self, nameaddr, SE_BUSCONFIG)) {
9359 			ret = NDI_SUCCESS;
9360 		}
9361 		break;
9362 
9363 	case BUS_CONFIG_ALL:
9364 	case BUS_CONFIG_DRIVER:
9365 		addr = kmem_zalloc(SCSI_MAXNAMELEN, KM_SLEEP);
9366 		/* create iport nodes for each scsi port/bus */
9367 		for (i = 0; i < num_iports; i++) {
9368 			bzero(addr, SCSI_MAXNAMELEN);
9369 			/* Prepend the iport name */
9370 			(void) snprintf(addr, SCSI_MAXNAMELEN, "iport@%s",
9371 			    iports[i]);
9372 			(void) scsi_hba_bus_config_port(self, addr,
9373 			    SE_BUSCONFIG);
9374 		}
9375 
9376 		kmem_free(addr, SCSI_MAXNAMELEN);
9377 		ret = NDI_SUCCESS;
9378 		break;
9379 	}
9380 	if (ret == NDI_SUCCESS) {
9381 #ifdef sparc
9382 		/*
9383 		 * Mask NDI_PROMNAME since PROM doesn't have iport
9384 		 * node at all.
9385 		 */
9386 		flags &= (~NDI_PROMNAME);
9387 #endif
9388 		flags |= NDI_MDI_FALLBACK;	/* devinfo&pathinfo children */
9389 		ret = ndi_busop_bus_config(self, flags, op,
9390 		    arg, childp, 0);
9391 	}
9392 	scsi_hba_devi_exit(self, circ);
9393 
9394 	ddi_prop_free(iports);
9395 
9396 	return (ret);
9397 }
9398 
9399 static int
9400 scsi_iportmap_config(void *arg, damap_t *mapp, damap_id_t tgtid)
9401 {
9402 	dev_info_t	*self = (dev_info_t *)arg;
9403 	int		circ;
9404 	char		nameaddr[SCSI_MAXNAMELEN];
9405 	char		*iport_addr;
9406 	dev_info_t	*childp;
9407 
9408 	scsi_hba_devi_enter(self, &circ);
9409 
9410 	iport_addr = damap_id2addr(mapp, tgtid);
9411 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9412 	    "%s @%s", damap_name(mapp), iport_addr));
9413 
9414 	(void) snprintf(nameaddr, sizeof (nameaddr), "iport@%s", iport_addr);
9415 	childp = scsi_hba_bus_config_port(self, nameaddr, SE_HP);
9416 	scsi_hba_devi_exit(self, circ);
9417 	return (childp != NULL ? DAM_SUCCESS : DAM_FAILURE);
9418 }
9419 
9420 static int
9421 scsi_iportmap_unconfig(void *arg, damap_t *mapp, damap_id_t tgtid)
9422 {
9423 	dev_info_t	*self = arg;
9424 	dev_info_t	*childp;	/* iport child of HBA node */
9425 	int		circ, empty;
9426 	char		*addr;
9427 	char		nameaddr[SCSI_MAXNAMELEN];
9428 	scsi_hba_tran_t	*tran;
9429 
9430 	addr = damap_id2addr(mapp, tgtid);
9431 	SCSI_HBA_LOG((_LOGIPT, self, NULL, "%s @%s", damap_name(mapp), addr));
9432 
9433 	(void) snprintf(nameaddr, sizeof (nameaddr), "iport@%s", addr);
9434 	scsi_hba_devi_enter(self, &circ);
9435 	if ((childp = ndi_devi_findchild(self, nameaddr)) == NULL) {
9436 		scsi_hba_devi_exit(self, circ);
9437 		return (DAM_FAILURE);
9438 	}
9439 
9440 	tran = ddi_get_driver_private(childp);
9441 	ASSERT(tran);
9442 
9443 	ndi_hold_devi(childp);
9444 	scsi_hba_devi_exit(self, circ);
9445 
9446 	/*
9447 	 * A begin/end (clear) against the iport's
9448 	 * tgtmap will trigger unconfigure of all
9449 	 * targets on the iport.
9450 	 *
9451 	 * Future: This bit of code only works if the
9452 	 * target map reporting style is are full
9453 	 * reports and not per-address. Maybe we
9454 	 * should plan on handling this by
9455 	 * auto-unconfiguration when destroying the
9456 	 * target map(s).
9457 	 */
9458 	(void) scsi_hba_tgtmap_set_begin(tran->tran_tgtmap);
9459 	(void) scsi_hba_tgtmap_set_end(tran->tran_tgtmap, 0);
9460 
9461 	/* wait for unconfigure */
9462 	(void) scsi_tgtmap_sync(tran->tran_tgtmap, 0);
9463 	empty = scsi_tgtmap_is_empty(tran->tran_tgtmap);
9464 
9465 	scsi_hba_devi_enter(self, &circ);
9466 	ndi_rele_devi(childp);
9467 
9468 	/* If begin/end/sync ends in empty map, offline/remove. */
9469 	if (empty) {
9470 		if (ndi_devi_offline(childp,
9471 		    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) == DDI_SUCCESS) {
9472 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
9473 			    "devinfo iport@%s offlined and removed",
9474 			    addr));
9475 		} else if (ndi_devi_device_remove(childp)) {
9476 			/* Offline/rem failed, note new device_remove */
9477 			SCSI_HBA_LOG((_LOGUNCFG, self, NULL,
9478 			    "devinfo iport@%s offline failed, "
9479 			    "device_remove", addr));
9480 		}
9481 	}
9482 	scsi_hba_devi_exit(self, circ);
9483 	return (empty ? DAM_SUCCESS : DAM_FAILURE);
9484 }
9485 
9486 
9487 int
9488 scsi_hba_iportmap_create(dev_info_t *self, int csync_usec, int settle_usec,
9489     scsi_hba_iportmap_t **handle)
9490 {
9491 	scsi_hba_tran_t		*tran;
9492 	damap_t			*mapp;
9493 	char			context[64];
9494 	impl_scsi_iportmap_t	*iportmap;
9495 
9496 	if (self == NULL || csync_usec == 0 ||
9497 	    settle_usec == 0 || handle == NULL)
9498 		return (DDI_FAILURE);
9499 
9500 	*handle = NULL;
9501 
9502 	if (scsi_hba_iport_unit_address(self) != NULL)
9503 		return (DDI_FAILURE);
9504 
9505 	tran = (scsi_hba_tran_t *)ddi_get_driver_private(self);
9506 	ASSERT(tran);
9507 	if (tran == NULL)
9508 		return (DDI_FAILURE);
9509 
9510 	(void) snprintf(context, sizeof (context), "%s%d.iportmap",
9511 	    ddi_driver_name(self), ddi_get_instance(self));
9512 
9513 	if (damap_create(context, DAMAP_REPORT_PERADDR, DAMAP_SERIALCONFIG,
9514 	    settle_usec, NULL, NULL, NULL, self,
9515 	    scsi_iportmap_config, scsi_iportmap_unconfig, &mapp) !=
9516 	    DAM_SUCCESS) {
9517 		return (DDI_FAILURE);
9518 	}
9519 	iportmap = kmem_zalloc(sizeof (*iportmap), KM_SLEEP);
9520 	iportmap->iportmap_hba_dip = self;
9521 	iportmap->iportmap_dam = mapp;
9522 
9523 	iportmap->iportmap_create_window = 1;	/* start with window */
9524 	iportmap->iportmap_create_time = ddi_get_lbolt64();
9525 	iportmap->iportmap_create_csync_usec = csync_usec;
9526 	iportmap->iportmap_settle_usec = settle_usec;
9527 	iportmap->iportmap_sync_cnt = 0;
9528 
9529 	tran->tran_iportmap = (scsi_hba_iportmap_t *)iportmap;
9530 	*handle = (scsi_hba_iportmap_t *)iportmap;
9531 
9532 	SCSI_HBA_LOG((_LOGIPT, self, NULL, "%s", damap_name(mapp)));
9533 	return (DDI_SUCCESS);
9534 }
9535 
9536 void
9537 scsi_hba_iportmap_destroy(scsi_hba_iportmap_t *handle)
9538 {
9539 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9540 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9541 
9542 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9543 	    "%s", damap_name(iportmap->iportmap_dam)));
9544 
9545 	damap_destroy(iportmap->iportmap_dam);
9546 	kmem_free(iportmap, sizeof (*iportmap));
9547 }
9548 
9549 int
9550 scsi_hba_iportmap_iport_add(scsi_hba_iportmap_t *handle,
9551     char *iport_addr, void *iport_priv)
9552 {
9553 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9554 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9555 
9556 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9557 	    "%s @%s", damap_name(iportmap->iportmap_dam), iport_addr));
9558 
9559 	return ((damap_addr_add(iportmap->iportmap_dam, iport_addr, NULL,
9560 	    NULL, iport_priv) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9561 }
9562 
9563 int
9564 scsi_hba_iportmap_iport_remove(scsi_hba_iportmap_t *handle,
9565     char *iport_addr)
9566 {
9567 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9568 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9569 
9570 	SCSI_HBA_LOG((_LOGIPT, self, NULL,
9571 	    "%s @%s", damap_name(iportmap->iportmap_dam), iport_addr));
9572 
9573 	return ((damap_addr_del(iportmap->iportmap_dam,
9574 	    iport_addr) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9575 }
9576 
9577 int
9578 scsi_hba_iportmap_lookup(scsi_hba_iportmap_t *handle,
9579     char *iport_addr)
9580 {
9581 	impl_scsi_iportmap_t	*iportmap = (impl_scsi_iportmap_t *)handle;
9582 	dev_info_t		*self = iportmap->iportmap_hba_dip;
9583 	damap_id_t		iportid;
9584 
9585 	iportid = damap_lookup(iportmap->iportmap_dam, iport_addr);
9586 	if (iportid != NODAM) {
9587 		SCSI_HBA_LOG((_LOG(3), self, NULL,
9588 		    "%s @%s found",
9589 		    damap_name(iportmap->iportmap_dam), iport_addr));
9590 		damap_id_rele(iportmap->iportmap_dam, iportid);
9591 		return (DDI_SUCCESS);
9592 	}
9593 
9594 	SCSI_HBA_LOG((_LOG(3), self, NULL,
9595 	    "%s @%s not found",
9596 	    damap_name(iportmap->iportmap_dam), iport_addr));
9597 	return (DDI_FAILURE);
9598 }
9599 
9600 
9601 static int
9602 scsi_lunmap_config(void *arg, damap_t *lundam, damap_id_t lunid)
9603 {
9604 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)arg;
9605 	scsi_hba_tran_t		*tran = tgtmap->tgtmap_tran;
9606 	dev_info_t		*self = tran->tran_iport_dip;
9607 	char			*addr;
9608 
9609 	addr = damap_id2addr(lundam, lunid);
9610 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9611 	    "%s @%s", damap_name(lundam), addr));
9612 	if (scsi_hba_bus_configone_addr(self, addr, SE_HP) != NULL)
9613 		return (DAM_SUCCESS);
9614 	else
9615 		return (DAM_FAILURE);
9616 }
9617 
9618 static int
9619 scsi_lunmap_unconfig(void *arg, damap_t *lundam, damap_id_t lunid)
9620 {
9621 	impl_scsi_tgtmap_t	*tgtmap = (impl_scsi_tgtmap_t *)arg;
9622 	scsi_hba_tran_t		*tran = tgtmap->tgtmap_tran;
9623 	dev_info_t		*self = tran->tran_iport_dip;
9624 	char			*addr;
9625 
9626 	addr = damap_id2addr(lundam, lunid);
9627 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s @%s", damap_name(lundam),
9628 	    addr));
9629 
9630 	scsi_hba_bus_unconfigone_addr(self, addr);
9631 	return (DAM_SUCCESS);
9632 }
9633 
9634 static int
9635 scsi_lunmap_create(dev_info_t *self, impl_scsi_tgtmap_t *tgtmap, char *taddr)
9636 {
9637 	char			context[64];
9638 	damap_t			*tgtdam;
9639 	damap_id_t		tgtid;
9640 	damap_t			*lundam;
9641 	int			optflags;
9642 
9643 	(void) snprintf(context, sizeof (context), "%s%d.%s.lunmap",
9644 	    ddi_driver_name(self), ddi_get_instance(self), taddr);
9645 
9646 	tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
9647 	tgtid = damap_lookup(tgtdam, taddr);
9648 	if (tgtid == NODAM) {
9649 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9650 		    "target %s not found", context));
9651 		return (DDI_FAILURE);
9652 	}
9653 
9654 	lundam = damap_id_priv_get(tgtdam, tgtid);
9655 	if (lundam) {
9656 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9657 		    "lunmap %s already created", context));
9658 		damap_id_rele(tgtdam, tgtid);
9659 		return (DDI_FAILURE);
9660 	}
9661 
9662 	optflags = (ddi_prop_get_int(DDI_DEV_T_ANY, self,
9663 	    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS, "scsi-enumeration",
9664 	    scsi_enumeration) & SCSI_ENUMERATION_MT_LUN_DISABLE) ?
9665 	    DAMAP_SERIALCONFIG : DAMAP_MTCONFIG;
9666 
9667 	/* NOTE: expected ref at tgtid/taddr: 2: caller + lookup. */
9668 	ASSERT(damap_id_ref(tgtdam, tgtid) == 2);
9669 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s creat, id %d ref %d",
9670 	    context, tgtid, damap_id_ref(tgtdam, tgtid)));
9671 
9672 	/* create lundam */
9673 	if (damap_create(context, DAMAP_REPORT_FULLSET, optflags, 1,
9674 	    NULL, NULL, NULL, tgtmap, scsi_lunmap_config, scsi_lunmap_unconfig,
9675 	    &lundam) != DAM_SUCCESS) {
9676 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9677 		    "%s create failed, id %d ref %d",
9678 		    context, tgtid, damap_id_ref(tgtdam, tgtid)));
9679 		damap_id_rele(tgtdam, tgtid);
9680 		return (DDI_FAILURE);
9681 	}
9682 
9683 	/*
9684 	 * Return with damap_id_hold at tgtid/taddr from damap_lookup to
9685 	 * account for damap_id_prv_set below.
9686 	 */
9687 	damap_id_priv_set(tgtdam, tgtid, lundam);
9688 	return (DDI_SUCCESS);
9689 }
9690 
9691 static void
9692 scsi_lunmap_destroy(dev_info_t *self, impl_scsi_tgtmap_t *tgtmap, char *taddr)
9693 {
9694 	char			context[64];
9695 	damap_t			*tgtdam;
9696 	damap_id_t		tgtid;
9697 	damap_t			*lundam;
9698 
9699 	(void) snprintf(context, sizeof (context), "%s%d.%s.lunmap",
9700 	    ddi_driver_name(self), ddi_get_instance(self), taddr);
9701 
9702 	tgtdam = tgtmap->tgtmap_dam[SCSI_TGT_SCSI_DEVICE];
9703 	tgtid = damap_lookup(tgtdam, taddr);
9704 	if (tgtid == NODAM) {
9705 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9706 		    "target %s not found", context));
9707 		return;
9708 	}
9709 
9710 	lundam = (damap_t *)damap_id_priv_get(tgtdam, tgtid);
9711 	if (lundam == NULL) {
9712 		damap_id_rele(tgtdam, tgtid);		/* from damap_lookup */
9713 		SCSI_HBA_LOG((_LOG(1), self, NULL,
9714 		    "lunmap %s already destroyed", context));
9715 		return;
9716 	}
9717 
9718 	/* NOTE: expected ref at tgtid/taddr: 3: priv_set + caller + lookup. */
9719 	ASSERT(damap_id_ref(tgtdam, tgtid) == 3);
9720 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s, id %d ref %d",
9721 	    damap_name(lundam), tgtid, damap_id_ref(tgtdam, tgtid)));
9722 
9723 	/*
9724 	 * A begin/end (clear) against a target's lunmap will trigger
9725 	 * unconfigure of all LUNs on the target.
9726 	 */
9727 	scsi_lunmap_set_begin(self, lundam);
9728 	scsi_lunmap_set_end(self, lundam);
9729 
9730 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9731 	    "%s sync begin", damap_name(lundam)));
9732 
9733 	(void) damap_sync(lundam, 0);	/* wait for unconfigure */
9734 
9735 	SCSI_HBA_LOG((_LOGLUN, self, NULL,
9736 	    "%s sync end", damap_name(lundam)));
9737 
9738 	damap_id_priv_set(tgtdam, tgtid, NULL);
9739 
9740 	/* release hold established by damap_lookup above */
9741 	damap_id_rele(tgtdam, tgtid);
9742 
9743 	/* release hold established since scsi_lunmap_create() */
9744 	damap_id_rele(tgtdam, tgtid);
9745 
9746 	damap_destroy(lundam);
9747 }
9748 
9749 static void
9750 scsi_lunmap_set_begin(dev_info_t *self, damap_t *lundam)
9751 {
9752 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s", damap_name(lundam)));
9753 
9754 	(void) damap_addrset_begin(lundam);
9755 }
9756 
9757 static int
9758 scsi_lunmap_set_add(dev_info_t *self, damap_t *lundam,
9759     char *taddr, scsi_lun64_t lun64, int sfunc)
9760 {
9761 	char	ua[SCSI_MAXNAMELEN];
9762 
9763 	/* make unit address string form of "@taddr,lun[,sfunc]" */
9764 	if (sfunc == -1)
9765 		(void) snprintf(ua, sizeof (ua), "%s,%" PRIx64, taddr, lun64);
9766 	else
9767 		(void) snprintf(ua, sizeof (ua), "%s,%" PRIx64 ",%x",
9768 		    taddr, lun64, sfunc);
9769 
9770 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s @%s", damap_name(lundam), ua));
9771 
9772 	return ((damap_addrset_add(lundam, ua, NULL, NULL,
9773 	    NULL) == DAM_SUCCESS) ? DDI_SUCCESS : DDI_FAILURE);
9774 }
9775 
9776 static void
9777 scsi_lunmap_set_end(dev_info_t *self, damap_t *lundam)
9778 {
9779 	SCSI_HBA_LOG((_LOGLUN, self, NULL, "%s", damap_name(lundam)));
9780 
9781 	(void) damap_addrset_end(lundam, 0);
9782 }
9783 
9784 int
9785 scsi_lunmap_lookup(dev_info_t *self, damap_t *lundam, char *addr)
9786 {
9787 	damap_id_t		lunid;
9788 
9789 	if ((lunid = damap_lookup(lundam, addr)) != NODAM) {
9790 		SCSI_HBA_LOG((_LOG(3), self, NULL,
9791 		    "%s @%s found", damap_name(lundam), addr));
9792 		damap_id_rele(lundam, lunid);
9793 		return (DDI_SUCCESS);
9794 	}
9795 
9796 	SCSI_HBA_LOG((_LOG(3), self, NULL,
9797 	    "%s @%s not found", damap_name(lundam), addr));
9798 	return (DDI_FAILURE);
9799 }
9800 
9801 /*
9802  * phymap implementation
9803  *
9804  * We manage the timed aggregation of phys into a phy map * by creating a
9805  * SAS port construct (based upon 'name' of "local,remote" SAS addresses)
9806  * upon the first link up. As time goes on additional phys may join that port.
9807  * After an appropriate amount of settle time, we trigger the activation
9808  * callback which will then take the resultant bit mask of phys (phymask) in
9809  * the SAS port and use that to call back to the callback function
9810  * provided by the additional caller.
9811  *
9812  * We cross check to make sure that phys only exist in one SAS port at a
9813  * time by having soft state for each phy point back to the created
9814  * SAS port.
9815  *
9816  * NOTE: Make SAS_PHY_UA_LEN max(SAS_PHY_PHYMASK_LEN, SAS_PHY_NAME_LEN)
9817  * so we have enough space if sas_phymap_bitset2phymaskua phymask address
9818  * is already in use, and we end up using port name as unit address.
9819  */
9820 #define	SAS_PHY_NAME_FMT	"%" PRIx64 ",%" PRIx64
9821 #define	SAS_PHY_NAME_LEN	(16 + 1 + 16 + 1)
9822 #define	SAS_PHY_NPHY		(SAS2_PHYNUM_MAX + 1)
9823 #define	SAS_PHY_PHYMASK_LEN	((roundup(SAS_PHY_NPHY, 4)) / 4)
9824 #if	(SAS_PHY_PHYMASK_LEN > SAS_PHY_NAME_LEN)
9825 #define	SAS_PHY_UA_LEN		SAS_PHY_PHYMASK_LEN
9826 #else
9827 #define	SAS_PHY_UA_LEN		SAS_PHY_NAME_LEN
9828 #endif
9829 typedef struct impl_sas_phymap {
9830 	dev_info_t			*phymap_self;
9831 
9832 	kmutex_t			phymap_lock;
9833 	damap_t				*phymap_dam;
9834 	void				*phymap_phy2name;
9835 	ddi_soft_state_bystr		*phymap_name2phys;	/* bitset */
9836 	ddi_soft_state_bystr		*phymap_name2ua;
9837 	ddi_soft_state_bystr		*phymap_ua2name;
9838 
9839 	/* Noisy phy information - ensure forward progress for noisy phys */
9840 	int				phymap_phy_max;		/* max phy# */
9841 	int				phymap_reports;		/* per period */
9842 	int				phymap_reports_max;	/* scales */
9843 	int				phymap_phys_noisy;	/* detected */
9844 
9845 	/* These are for callbacks to the consumer. */
9846 	sas_phymap_activate_cb_t	phymap_acp;
9847 	sas_phymap_deactivate_cb_t	phymap_dcp;
9848 	void				*phymap_private;
9849 } impl_sas_phymap_t;
9850 
9851 /* Detect noisy phy: max changes per stabilization period per phy. */
9852 static int sas_phymap_phy_max_factor = 16;
9853 
9854 /*
9855  * Convert bitset into a unit-address string. The maximum string length would
9856  * be the maximum number of phys, rounded up by 4 and divided by 4.
9857  */
9858 static void
9859 sas_phymap_bitset2phymaskua(bitset_t *phys, char *buf)
9860 {
9861 	char			*ptr;
9862 	int			grp;
9863 	int			cur;
9864 	uint_t			bit;
9865 
9866 	bit = roundup(SAS_PHY_NPHY, 4);
9867 	grp = 4;
9868 	ptr = buf;
9869 	cur = 0;
9870 	do {
9871 		bit -= 1;
9872 		grp -= 1;
9873 		if (bitset_in_set(phys, bit)) {
9874 			cur |= (1 << grp);
9875 		}
9876 		if (grp == 0) {
9877 			grp = 4;
9878 			if (cur || ptr != buf) {
9879 				*ptr++ = "0123456789abcdef"[cur];
9880 				*ptr = 0;
9881 			}
9882 			cur = 0;
9883 		}
9884 	} while (bit != 0);
9885 	if (ptr == buf) {
9886 		*ptr++ = '0';
9887 		*ptr = 0;
9888 	}
9889 }
9890 
9891 static int
9892 sas_phymap_config(void *arg, damap_t *phydam, damap_id_t phyid)
9893 {
9894 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)arg;
9895 	char			*context = damap_name(phymap->phymap_dam);
9896 	char			*damn;
9897 	char			*name;
9898 	bitset_t		*phys;
9899 	char			*ua;
9900 	void			*ua_priv;
9901 
9902 	ASSERT(context);
9903 
9904 	mutex_enter(&phymap->phymap_lock);
9905 	phymap->phymap_reports = phymap->phymap_phys_noisy = 0;
9906 
9907 	/* Get the name ("local,remote" address string) from damap. */
9908 	damn = damap_id2addr(phydam, phyid);
9909 
9910 	/* Get the bitset of phys currently forming the port. */
9911 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, damn);
9912 	if (phys == NULL) {
9913 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: no phys",
9914 		    context, damn));
9915 		mutex_exit(&phymap->phymap_lock);
9916 		return (DAM_FAILURE);
9917 	}
9918 
9919 	/* allocate, get, and initialize name index of name2ua map */
9920 	if (ddi_soft_state_bystr_zalloc(phymap->phymap_name2ua, damn) !=
9921 	    DDI_SUCCESS) {
9922 		SCSI_HBA_LOG((_LOG_NF(WARN),
9923 		    "%s: %s: failed name2ua alloc", context, damn));
9924 		mutex_exit(&phymap->phymap_lock);
9925 		return (DAM_FAILURE);
9926 	}
9927 	if (!(ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, damn))) {
9928 		SCSI_HBA_LOG((_LOG_NF(WARN),
9929 		    "%s: %s: no name2ua", context, damn));
9930 		mutex_exit(&phymap->phymap_lock);
9931 		return (DAM_FAILURE);
9932 	}
9933 	sas_phymap_bitset2phymaskua(phys, ua);		/* set ua */
9934 
9935 	/* see if phymask ua index already allocated in ua2name map */
9936 	if (name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua)) {
9937 		/*
9938 		 * The 'phymask' sas_phymap_bitset2phymaskua ua is
9939 		 * already in use. This means that original phys have
9940 		 * formed into a new port, and that the original port
9941 		 * still exists (it has migrated to some completely
9942 		 * different set of phys). In this corner-case we use
9943 		 * "local,remote" name as a 'temporary' unit address.
9944 		 * Reset ua in name2ua map.
9945 		 */
9946 		(void) strlcpy(ua, damn, SAS_PHY_NAME_LEN);
9947 		name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9948 		if (name) {
9949 			/* The "local,remote" ua should be new... */
9950 			SCSI_HBA_LOG((_LOG_NF(WARN),
9951 			    "%s: %s ua already configured",
9952 			    context, ua));
9953 			mutex_exit(&phymap->phymap_lock);
9954 			return (DAM_SUCCESS);
9955 		}
9956 	}
9957 
9958 	/* allocate, get, and init ua index of ua2name map */
9959 	if (ddi_soft_state_bystr_zalloc(phymap->phymap_ua2name, ua) !=
9960 	    DDI_SUCCESS) {
9961 		ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
9962 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: failed ua2name alloc",
9963 		    context, damn));
9964 		mutex_exit(&phymap->phymap_lock);
9965 		return (DAM_FAILURE);
9966 	}
9967 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
9968 	if (name == NULL) {
9969 		ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
9970 		SCSI_HBA_LOG((_LOG_NF(WARN),
9971 		    "%s: %s: no ua2name", context, ua));
9972 		mutex_exit(&phymap->phymap_lock);
9973 		return (DAM_FAILURE);
9974 	}
9975 
9976 	/* set name in ua2name map */
9977 	(void) strlcpy(name, damn, SAS_PHY_NAME_LEN);
9978 
9979 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9980 	    "%s: %s: ua %s: activate", context, damn, ua));
9981 
9982 	if (phymap->phymap_acp) {
9983 		/*
9984 		 * drop our lock and invoke the activation callback
9985 		 */
9986 		mutex_exit(&phymap->phymap_lock);
9987 		ua_priv = NULL;
9988 		(phymap->phymap_acp)(phymap->phymap_private, ua, &ua_priv);
9989 		mutex_enter(&phymap->phymap_lock);
9990 		damap_id_priv_set(phydam, phyid, ua_priv);
9991 	}
9992 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
9993 	    "%s: %s: ua %s: activate complete", context, damn, ua));
9994 	mutex_exit(&phymap->phymap_lock);
9995 	return (DAM_SUCCESS);
9996 }
9997 
9998 /*ARGSUSED*/
9999 static int
10000 sas_phymap_unconfig(void *arg, damap_t *phydam, damap_id_t phyid)
10001 {
10002 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)arg;
10003 	char			*context = damap_name(phymap->phymap_dam);
10004 	char			*damn;
10005 	char			*ua;
10006 	void			*ua_priv;
10007 
10008 	ASSERT(context);
10009 
10010 	mutex_enter(&phymap->phymap_lock);
10011 	phymap->phymap_reports = phymap->phymap_phys_noisy = 0;
10012 
10013 	/* Get the name ("local,remote" address string) from damap. */
10014 	damn = damap_id2addr(phydam, phyid);
10015 
10016 	if (!(ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, damn))) {
10017 		SCSI_HBA_LOG((_LOG_NF(WARN),
10018 		    "%s: %s: no name2ua", context, damn));
10019 		mutex_exit(&phymap->phymap_lock);
10020 		return (DAM_FAILURE);
10021 	}
10022 
10023 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
10024 	    "%s: %s: ua %s: deactivate", context, damn, ua));
10025 	if (phymap->phymap_dcp) {
10026 		ua_priv = damap_id_priv_get(phydam, phyid);
10027 		mutex_exit(&phymap->phymap_lock);
10028 		(phymap->phymap_dcp)(phymap->phymap_private, ua, ua_priv);
10029 		mutex_enter(&phymap->phymap_lock);
10030 	}
10031 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
10032 	    "%s: %s: ua %s: deactivate complete", context, damn, ua));
10033 
10034 	/* delete ua<->name mappings */
10035 	ddi_soft_state_bystr_free(phymap->phymap_ua2name, ua);
10036 	ddi_soft_state_bystr_free(phymap->phymap_name2ua, damn);
10037 	mutex_exit(&phymap->phymap_lock);
10038 	return (DAM_SUCCESS);
10039 }
10040 
10041 int
10042 sas_phymap_create(dev_info_t *self, int settle_usec,
10043     sas_phymap_mode_t mode, void *mode_argument, void *phymap_priv,
10044     sas_phymap_activate_cb_t  activate_cb,
10045     sas_phymap_deactivate_cb_t deactivate_cb,
10046     sas_phymap_t **handlep)
10047 {
10048 	_NOTE(ARGUNUSED(mode_argument));
10049 	char			context[64];
10050 	impl_sas_phymap_t	*phymap;
10051 
10052 	if (self == NULL || settle_usec == 0 || handlep == NULL)
10053 		return (DDI_FAILURE);
10054 
10055 	if (mode != PHYMAP_MODE_SIMPLE)
10056 		return (DDI_FAILURE);
10057 
10058 	phymap = kmem_zalloc(sizeof (*phymap), KM_SLEEP);
10059 	phymap->phymap_self = self;
10060 	phymap->phymap_reports_max = 1 * sas_phymap_phy_max_factor;
10061 	phymap->phymap_acp = activate_cb;
10062 	phymap->phymap_dcp = deactivate_cb;
10063 	phymap->phymap_private = phymap_priv;
10064 	mutex_init(&phymap->phymap_lock, NULL, MUTEX_DRIVER, NULL);
10065 
10066 	(void) snprintf(context, sizeof (context), "%s%d.phymap",
10067 	    ddi_driver_name(self), ddi_get_instance(self));
10068 	SCSI_HBA_LOG((_LOGPHY, self, NULL, "%s", context));
10069 
10070 	if (damap_create(context, DAMAP_REPORT_PERADDR, DAMAP_SERIALCONFIG,
10071 	    settle_usec, NULL, NULL, NULL,
10072 	    phymap, sas_phymap_config, sas_phymap_unconfig,
10073 	    &phymap->phymap_dam) != DAM_SUCCESS)
10074 		goto fail;
10075 
10076 	if (ddi_soft_state_init(&phymap->phymap_phy2name,
10077 	    SAS_PHY_NAME_LEN, SAS_PHY_NPHY) != 0)
10078 		goto fail;
10079 
10080 	if (ddi_soft_state_bystr_init(&phymap->phymap_name2phys,
10081 	    sizeof (bitset_t), SAS_PHY_NPHY) != 0)
10082 		goto fail;
10083 
10084 	if (ddi_soft_state_bystr_init(&phymap->phymap_name2ua,
10085 	    SAS_PHY_UA_LEN, SAS_PHY_NPHY) != 0)
10086 		goto fail;
10087 	if (ddi_soft_state_bystr_init(&phymap->phymap_ua2name,
10088 	    SAS_PHY_NAME_LEN, SAS_PHY_NPHY) != 0)
10089 		goto fail;
10090 
10091 	*handlep = (sas_phymap_t *)phymap;
10092 	return (DDI_SUCCESS);
10093 
10094 fail:	sas_phymap_destroy((sas_phymap_t *)phymap);
10095 	*handlep = NULL;
10096 	return (DDI_FAILURE);
10097 }
10098 
10099 void
10100 sas_phymap_destroy(sas_phymap_t *handle)
10101 {
10102 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10103 	char			*context;
10104 
10105 	context = phymap->phymap_dam ?
10106 	    damap_name(phymap->phymap_dam) : "unknown";
10107 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s", context));
10108 
10109 	if (phymap->phymap_ua2name)
10110 		ddi_soft_state_bystr_fini(&phymap->phymap_ua2name);
10111 	if (phymap->phymap_name2ua)
10112 		ddi_soft_state_bystr_fini(&phymap->phymap_name2ua);
10113 
10114 	if (phymap->phymap_name2phys)
10115 		ddi_soft_state_bystr_fini(&phymap->phymap_name2phys);
10116 
10117 	if (phymap->phymap_phy2name)
10118 		ddi_soft_state_fini(&phymap->phymap_phy2name);
10119 
10120 	if (phymap->phymap_dam)
10121 		damap_destroy(phymap->phymap_dam);
10122 	mutex_destroy(&phymap->phymap_lock);
10123 	kmem_free(phymap, sizeof (*phymap));
10124 }
10125 
10126 
10127 int
10128 sas_phymap_phy_add(sas_phymap_t *handle,
10129     int phy, uint64_t local, uint64_t remote)
10130 {
10131 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10132 	char			*context = damap_name(phymap->phymap_dam);
10133 	char			port[SAS_PHY_NAME_LEN];
10134 	char			*name;
10135 	bitset_t		*phys;
10136 	int			phy2name_allocated = 0;
10137 	int			name2phys_allocated = 0;
10138 	int			rv;
10139 
10140 	/* Create the SAS port name from the local and remote addresses. */
10141 	(void) snprintf(port, SAS_PHY_NAME_LEN, SAS_PHY_NAME_FMT,
10142 	    local, remote);
10143 
10144 	mutex_enter(&phymap->phymap_lock);
10145 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s: %s: add phy %d",
10146 	    context, port, phy));
10147 
10148 	/* Check for conflict in phy2name map */
10149 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
10150 	if (name) {
10151 		if (strcmp(name, port) != 0)
10152 			SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: add phy %d: "
10153 			    "already in %s", context, port, phy, name));
10154 		else
10155 			SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: add phy %d: "
10156 			    "duplicate add", context, port, phy));
10157 		mutex_exit(&phymap->phymap_lock);
10158 		return (DDI_FAILURE);
10159 	}
10160 
10161 	/* allocate, get, and initialize phy index of phy2name map */
10162 	if (ddi_soft_state_zalloc(
10163 	    phymap->phymap_phy2name, phy) != DDI_SUCCESS) {
10164 		SCSI_HBA_LOG((_LOG_NF(WARN),
10165 		    "%s: %s: failed phy2name alloc", context, port));
10166 		goto fail;
10167 	}
10168 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
10169 	if (name == NULL) {
10170 		SCSI_HBA_LOG((_LOG_NF(WARN),
10171 		    "%s: %s: no phy2name", context, port));
10172 		goto fail;
10173 	}
10174 	phy2name_allocated = 1;
10175 	(void) strlcpy(name, port, SAS_PHY_NAME_LEN);	/* set name */
10176 
10177 	/* Find/alloc, initialize name index of name2phys map */
10178 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
10179 	if (phys == NULL) {
10180 		if (ddi_soft_state_bystr_zalloc(phymap->phymap_name2phys,
10181 		    name) != DDI_SUCCESS) {
10182 			SCSI_HBA_LOG((_LOG_NF(WARN),
10183 			    "%s: %s: failed name2phys alloc", context, name));
10184 			goto fail;
10185 		}
10186 		phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
10187 		if (phys == NULL) {
10188 			SCSI_HBA_LOG((_LOG_NF(WARN),
10189 			    "%s: %s: no name2phys", context, name));
10190 			goto fail;
10191 		}
10192 		name2phys_allocated = 1;
10193 
10194 		/* Initialize bitset of phys */
10195 		bitset_init(phys);
10196 		bitset_resize(phys, SAS_PHY_NPHY);
10197 
10198 		/* NOTE: no bitset_fini of phys needed */
10199 	}
10200 	ASSERT(phys);
10201 
10202 	/* Reflect 'add' in phys bitset. */
10203 	if (bitset_atomic_test_and_add(phys, phy) < 0) {
10204 		/* It is an error if the phy was already recorded. */
10205 		SCSI_HBA_LOG((_LOG_NF(WARN),
10206 		    "%s: %s: phy bit %d already in port", context, name, phy));
10207 		goto fail;
10208 	}
10209 
10210 	/*
10211 	 * Check to see if we have a new phy_max for this map, and if so
10212 	 * scale phymap_reports_max to the new number of phys.
10213 	 */
10214 	if (phy > phymap->phymap_phy_max) {
10215 		phymap->phymap_phy_max = phy + 1;
10216 		phymap->phymap_reports_max = phymap->phymap_phy_max *
10217 		    sas_phymap_phy_max_factor;
10218 	}
10219 
10220 	/*
10221 	 * If we have not reached phymap_reports_max, start/restart the
10222 	 * activate timer. Otherwise, if phymap->phymap_reports add/rem reports
10223 	 * ever exceeds phymap_reports_max due to noisy phys, then report the
10224 	 * noise and force stabilization by stopping reports into the damap.
10225 	 *
10226 	 * The first config/unconfig callout out of the damap will reset
10227 	 * phymap->phymap_reports.
10228 	 */
10229 	rv = DDI_SUCCESS;
10230 	if (phymap->phymap_reports++ < phymap->phymap_reports_max) {
10231 		if (damap_addr_add(phymap->phymap_dam, name,
10232 		    NULL, NULL, NULL) == DAM_SUCCESS) {
10233 			SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
10234 			    "%s: %s: damap_addr_add", context, name));
10235 		} else {
10236 			SCSI_HBA_LOG((_LOG_NF(WARN),
10237 			    "%s: %s: damap_addr_add failed", context, name));
10238 			rv = DDI_FAILURE;
10239 		}
10240 	} else {
10241 		phymap->phymap_phys_noisy++;
10242 		if (phymap->phymap_phys_noisy == 1)
10243 			SCSI_HBA_LOG((_LOG_NF(WARN),
10244 			    "%s: %s: noisy phys", context, name));
10245 	}
10246 	mutex_exit(&phymap->phymap_lock);
10247 	return (rv);
10248 
10249 fail:	if (phy2name_allocated)
10250 		ddi_soft_state_free(phymap->phymap_phy2name, phy);
10251 	if (name2phys_allocated)
10252 		ddi_soft_state_bystr_free(phymap->phymap_name2phys, name);
10253 	mutex_exit(&phymap->phymap_lock);
10254 	return (DDI_FAILURE);
10255 }
10256 
10257 int
10258 sas_phymap_phy_rem(sas_phymap_t *handle, int phy)
10259 {
10260 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10261 	char			*context = damap_name(phymap->phymap_dam);
10262 	char			*name;
10263 	bitset_t		*phys;
10264 	int			rv = DDI_FAILURE;
10265 
10266 	ASSERT(context);
10267 
10268 	mutex_enter(&phymap->phymap_lock);
10269 	phymap->phymap_reports++;
10270 
10271 	/* Find and free phy index of phy2name map */
10272 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
10273 	if (name == NULL) {
10274 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: rem phy %d: never added",
10275 		    context, phy));
10276 		goto fail;
10277 	}
10278 	/* NOTE: always free phy index of phy2name map before return... */
10279 
10280 	SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL, "%s: %s: rem phy %d",
10281 	    context, name, phy));
10282 
10283 	/* Get bitset of phys currently associated with named port. */
10284 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
10285 	if (phys == NULL) {
10286 		SCSI_HBA_LOG((_LOG_NF(WARN), "%s: %s: name2phys failed",
10287 		    context, name));
10288 		goto fail;
10289 	}
10290 
10291 	/* Reflect 'rem' in phys bitset. */
10292 	if (bitset_atomic_test_and_del(phys, phy) < 0) {
10293 		/* It is an error if the phy wasn't one of the port's phys. */
10294 		SCSI_HBA_LOG((_LOG_NF(WARN),
10295 		    "%s: %s: phy bit %d not in port", context, name, phy));
10296 		goto fail;
10297 	}
10298 
10299 	/* If this was the last phy in the port, start the deactivate timer. */
10300 	if (bitset_is_null(phys) &&
10301 	    (phymap->phymap_reports++ < phymap->phymap_reports_max)) {
10302 		if (damap_addr_del(phymap->phymap_dam, name) == DAM_SUCCESS) {
10303 			SCSI_HBA_LOG((_LOGPHY, phymap->phymap_self, NULL,
10304 			    "%s: %s: damap_addr_del", context, name));
10305 		} else {
10306 			SCSI_HBA_LOG((_LOG_NF(WARN),
10307 			    "%s: %s: damap_addr_del failure", context, name));
10308 			goto fail;
10309 		}
10310 	}
10311 	rv = DDI_SUCCESS;
10312 
10313 	/* free phy index of phy2name map */
10314 fail:	if (name)
10315 		ddi_soft_state_free(phymap->phymap_phy2name, phy); /* free */
10316 	mutex_exit(&phymap->phymap_lock);
10317 	return (rv);
10318 }
10319 
10320 char *
10321 sas_phymap_lookup_ua(sas_phymap_t *handle, uint64_t local, uint64_t remote)
10322 {
10323 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10324 	char			*context = damap_name(phymap->phymap_dam);
10325 	char			name[SAS_PHY_NAME_LEN];
10326 	char			*ua;
10327 
10328 	ASSERT(context);
10329 
10330 	(void) snprintf(name, SAS_PHY_NAME_LEN, SAS_PHY_NAME_FMT,
10331 	    local, remote);
10332 
10333 	mutex_enter(&phymap->phymap_lock);
10334 	ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, name);
10335 	SCSI_HBA_LOG((_LOG(3), phymap->phymap_self, NULL,
10336 	    "%s: %s: ua %s", context, name, ua ? ua : "NULL"));
10337 	mutex_exit(&phymap->phymap_lock);
10338 	return (ua);
10339 }
10340 
10341 void *
10342 sas_phymap_lookup_uapriv(sas_phymap_t *handle, char *ua)
10343 {
10344 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10345 	char			*context = damap_name(phymap->phymap_dam);
10346 	char			*name;
10347 	damap_id_t		phyid;
10348 	void			*ua_priv = NULL;
10349 
10350 	ASSERT(context);
10351 
10352 	mutex_enter(&phymap->phymap_lock);
10353 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
10354 	if (name) {
10355 		phyid = damap_lookup(phymap->phymap_dam, name);
10356 		if (phyid != NODAM) {
10357 			ua_priv = damap_id_priv_get(phymap->phymap_dam, phyid);
10358 			damap_id_rele(phymap->phymap_dam, phyid);
10359 		}
10360 	}
10361 
10362 	SCSI_HBA_LOG((_LOG(3), phymap->phymap_self, NULL,
10363 	    "%s: %s: ua %s ua_priv %p", context, name,
10364 	    ua ? ua : "NULL", ua_priv));
10365 	mutex_exit(&phymap->phymap_lock);
10366 	return (ua_priv);
10367 }
10368 
10369 int
10370 sas_phymap_uahasphys(sas_phymap_t *handle, char *ua)
10371 {
10372 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10373 	char			*name;
10374 	bitset_t		*phys;
10375 	int			n = 0;
10376 
10377 	mutex_enter(&phymap->phymap_lock);
10378 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
10379 	if (name) {
10380 		phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
10381 		if (phys)
10382 			n = bitset_is_null(phys) ? 0 : 1;
10383 	}
10384 	mutex_exit(&phymap->phymap_lock);
10385 	return (n);
10386 }
10387 
10388 sas_phymap_phys_t *
10389 sas_phymap_ua2phys(sas_phymap_t *handle, char *ua)
10390 {
10391 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10392 	char			*name;
10393 	bitset_t		*phys;
10394 	bitset_t		*cphys = NULL;
10395 
10396 	mutex_enter(&phymap->phymap_lock);
10397 	name = ddi_soft_state_bystr_get(phymap->phymap_ua2name, ua);
10398 	if (name == NULL)
10399 		goto fail;
10400 
10401 	phys = ddi_soft_state_bystr_get(phymap->phymap_name2phys, name);
10402 	if (phys == NULL)
10403 		goto fail;
10404 
10405 	/* dup the phys and return */
10406 	cphys = kmem_alloc(sizeof (*cphys), KM_SLEEP);
10407 	bitset_init(cphys);
10408 	bitset_resize(cphys, SAS_PHY_NPHY);
10409 	bitset_copy(phys, cphys);
10410 
10411 fail:	mutex_exit(&phymap->phymap_lock);
10412 	return ((sas_phymap_phys_t *)cphys);
10413 }
10414 
10415 int
10416 sas_phymap_phys_next(sas_phymap_phys_t *phys)
10417 {
10418 	bitset_t	*cphys = (bitset_t *)phys;
10419 	int		phy;
10420 
10421 	phy = bitset_find(cphys);
10422 	if (phy != -1)
10423 		bitset_del(cphys, phy);
10424 	return (phy);
10425 }
10426 
10427 void
10428 sas_phymap_phys_free(sas_phymap_phys_t *phys)
10429 {
10430 	bitset_t	*cphys = (bitset_t *)phys;
10431 
10432 	if (cphys) {
10433 		bitset_fini(cphys);
10434 		kmem_free(cphys, sizeof (*cphys));
10435 	}
10436 }
10437 
10438 char *
10439 sas_phymap_phy2ua(sas_phymap_t *handle, int phy)
10440 {
10441 	impl_sas_phymap_t	*phymap = (impl_sas_phymap_t *)handle;
10442 	char			*name;
10443 	char			*ua;
10444 	char			*rua = NULL;
10445 
10446 	mutex_enter(&phymap->phymap_lock);
10447 	name = ddi_get_soft_state(phymap->phymap_phy2name, phy);
10448 	if (name == NULL)
10449 		goto fail;
10450 	ua = ddi_soft_state_bystr_get(phymap->phymap_name2ua, name);
10451 	if (ua == NULL)
10452 		goto fail;
10453 
10454 	/* dup the ua and return */
10455 	rua = strdup(ua);
10456 
10457 fail:	mutex_exit(&phymap->phymap_lock);
10458 	return (rua);
10459 }
10460 
10461 void
10462 sas_phymap_ua_free(char *ua)
10463 {
10464 	if (ua)
10465 		strfree(ua);
10466 }
10467