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