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