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