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