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