1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
25 * Copyright (c) 2016 by Delphix. All rights reserved.
26 */
27
28#include <sys/note.h>
29
30/*
31 * Generic SCSI Host Bus Adapter interface implementation
32 */
33#include <sys/scsi/scsi.h>
34#include <sys/scsi/generic/sas.h>
35#include <sys/file.h>
36#include <sys/disp.h>			/* for minclsyspri */
37#include <sys/ddi_impldefs.h>
38#include <sys/ndi_impldefs.h>
39#include <sys/sunndi.h>
40#include <sys/ddi.h>
41#include <sys/sunmdi.h>
42#include <sys/mdi_impldefs.h>
43#include <sys/callb.h>
44#include <sys/epm.h>
45#include <sys/damap.h>
46#include <sys/time.h>
47#include <sys/sunldi.h>
48#include <sys/fm/protocol.h>
49
50extern struct scsi_pkt *scsi_init_cache_pkt(struct scsi_address *,
51		    struct scsi_pkt *, struct buf *, int, int, int, int,
52		    int (*)(caddr_t), caddr_t);
53extern void	scsi_free_cache_pkt(struct scsi_address *, struct scsi_pkt *);
54extern void	scsi_cache_dmafree(struct scsi_address *, struct scsi_pkt *);
55extern void	scsi_sync_cache_pkt(struct scsi_address *, struct scsi_pkt *);
56extern int	modrootloaded;
57
58/*
59 * Round up all allocations so that we can guarantee
60 * long-long alignment.  This is the same alignment
61 * provided by kmem_alloc().
62 */
63#define	ROUNDUP(x)	(((x) + 0x07) & ~0x07)
64
65/* Magic number to track correct allocations in wrappers */
66#define	PKT_WRAPPER_MAGIC	0xa110ced	/* alloced correctly */
67
68kmutex_t	scsi_flag_nointr_mutex;
69kcondvar_t	scsi_flag_nointr_cv;
70kmutex_t	scsi_log_mutex;
71
72/* asynchronous probe barrier deletion data structures */
73static kmutex_t	scsi_hba_barrier_mutex;
74static kcondvar_t	scsi_hba_barrier_cv;
75static struct scsi_hba_barrier {
76	struct scsi_hba_barrier	*barrier_next;
77	clock_t			barrier_endtime;
78	dev_info_t		*barrier_probe;
79}		*scsi_hba_barrier_list;
80static int	scsi_hba_devi_is_barrier(dev_info_t *probe);
81static void	scsi_hba_barrier_tran_tgt_free(dev_info_t *probe);
82static void	scsi_hba_barrier_add(dev_info_t *probe, int seconds);
83static int	scsi_hba_remove_node(dev_info_t *child);
84static void	scsi_hba_barrier_daemon(void *arg);
85
86/* LUN-change ASC/ASCQ processing data structures (stage1 and stage2) */
87static kmutex_t		scsi_lunchg1_mutex;
88static kcondvar_t	scsi_lunchg1_cv;
89static struct scsi_pkt	*scsi_lunchg1_list;
90static void		scsi_lunchg1_daemon(void *arg);
91static kmutex_t		scsi_lunchg2_mutex;
92static kcondvar_t	scsi_lunchg2_cv;
93static struct scsi_lunchg2 {
94	struct scsi_lunchg2	*lunchg2_next;
95	char			*lunchg2_path;
96}			*scsi_lunchg2_list;
97static void		scsi_lunchg2_daemon(void *arg);
98
99static int	scsi_findchild(dev_info_t *self, char *name, char *addr,
100    int init, dev_info_t **dchildp, mdi_pathinfo_t **pchildp, int *ppi);
101
102/* return value defines for scsi_findchild */
103#define	CHILD_TYPE_NONE		0
104#define	CHILD_TYPE_DEVINFO	1
105#define	CHILD_TYPE_PATHINFO	2
106
107/*
108 * Enumeration code path currently being followed. SE_BUSCONFIG results in
109 * DEVI_SID_NODEID, and SE_HP (hotplug) results in DEVI_SID_HP_NODEID.
110 *
111 * Since hotplug enumeration is based on information obtained from hardware
112 * (tgtmap/report_lun) the type/severity of enumeration error messages is
113 * sometimes based SE_HP (indirectly via ndi_dev_is_hotplug_node()). By
114 * convention, these messages are all produced by scsi_enumeration_failed().
115 */
116typedef enum { SE_BUSCONFIG = 0, SE_HP = 1 } scsi_enum_t;
117
118/* compatible properties of driver to use during probe/enumeration operations */
119static char	*compatible_probe = "scsa,probe";
120static char	*compatible_nodev = "scsa,nodev";
121static char	*scsi_probe_ascii[] = SCSIPROBE_ASCII;
122
123/* number of LUNs we attempt to get on the first SCMD_REPORT_LUNS command */
124int	scsi_lunrpt_default_max = 256;
125int	scsi_lunrpt_timeout = 3;	/* seconds */
126
127/*
128 * Only enumerate one lun if reportluns fails on a SCSI_VERSION_3 device
129 * (tunable based on calling context).
130 */
131int	scsi_lunrpt_failed_do1lun = (1 << SE_HP);
132
133/* 'scsi-binding-set' value for legacy enumerated 'spi' transports */
134char	*scsi_binding_set_spi = "spi";
135
136/* enable NDI_DEVI_DEBUG for bus_[un]config operations */
137int	scsi_hba_bus_config_debug = 0;
138
139/* DEBUG: enable NDI_DEVI_REMOVE for bus_unconfig of dynamic node */
140int	scsi_hba_bus_unconfig_remove = 0;
141
142/* number of probe serilization messages */
143int	scsi_hba_wait_msg = 5;
144
145/*
146 * Establish the timeout used to cache (in the probe node) the fact that the
147 * device does not exist. This replaces the target specific probe cache.
148 */
149int	scsi_hba_barrier_timeout = (60);		/* seconds */
150
151#ifdef	DEBUG
152int	scsi_hba_bus_config_failure_msg = 0;
153int	scsi_hba_bus_config_failure_dbg = 0;
154int	scsi_hba_bus_config_success_msg = 0;
155int	scsi_hba_bus_config_success_dbg = 0;
156#endif	/* DEBUG */
157
158/*
159 * Structure for scsi_hba_iportmap_* implementation/wrap.
160 */
161typedef struct impl_scsi_iportmap {
162	dev_info_t	*iportmap_hba_dip;
163	damap_t		*iportmap_dam;
164	int		iportmap_create_window;
165	uint64_t	iportmap_create_time;		/* clock64_t */
166	int		iportmap_create_csync_usec;
167	int		iportmap_settle_usec;
168	int		iportmap_sync_cnt;
169} impl_scsi_iportmap_t;
170
171/*
172 * Structure for scsi_hba_tgtmap_* implementation/wrap.
173 *
174 * Every call to scsi_hba_tgtmap_set_begin will increment tgtmap_reports,
175 * and a call to scsi_hba_tgtmap_set_end will reset tgtmap_reports to zero.
176 * If, in scsi_hba_tgtmap_set_begin, we detect a tgtmap_reports value of
177 * scsi_hba_tgtmap_reports_max we produce a message to indicate that
178 * the caller is never completing an observation (i.e. we are not making
179 * any forward progress). If this message occurs, it indicates that the
180 * solaris hotplug ramifications at the target and lun level are no longer
181 * tracking.
182 *
183 * NOTE: LUNMAPSIZE OK for now, but should be dynamic in reportlun code.
184 */
185typedef struct impl_scsi_tgtmap {
186	scsi_hba_tran_t *tgtmap_tran;
187	int		tgtmap_reports;			/* _begin, no _end */
188	int		tgtmap_noisy;
189	scsi_tgt_activate_cb_t		tgtmap_activate_cb;
190	scsi_tgt_deactivate_cb_t	tgtmap_deactivate_cb;
191	void		*tgtmap_mappriv;
192	damap_t		*tgtmap_dam[SCSI_TGT_NTYPES];
193	int		tgtmap_create_window;
194	uint64_t	tgtmap_create_time;		/* clock64_t */
195	int		tgtmap_create_csync_usec;
196	int		tgtmap_settle_usec;
197	int		tgtmap_sync_cnt;
198} impl_scsi_tgtmap_t;
199#define	LUNMAPSIZE 256		/* 256 LUNs/target */
200
201/* Produce warning if number of begins without an end exceed this value */
202int	scsi_hba_tgtmap_reports_max = 256;
203
204static int	scsi_tgtmap_sync(scsi_hba_tgtmap_t *, int);
205
206/* Default settle_usec damap_sync factor */
207int	scsi_hba_map_settle_f = 10;
208
209
210/* Prototype for static dev_ops devo_*() functions */
211static int	scsi_hba_info(
212			dev_info_t		*self,
213			ddi_info_cmd_t		infocmd,
214			void			*arg,
215			void			**result);
216
217/* Prototypes for static bus_ops bus_*() functions */
218static int	scsi_hba_bus_ctl(
219			dev_info_t		*self,
220			dev_info_t		*child,
221			ddi_ctl_enum_t		op,
222			void			*arg,
223			void			*result);
224
225static int	scsi_hba_map_fault(
226			dev_info_t		*self,
227			dev_info_t		*child,
228			struct hat		*hat,
229			struct seg		*seg,
230			caddr_t			addr,
231			struct devpage		*dp,
232			pfn_t			pfn,
233			uint_t			prot,
234			uint_t			lock);
235
236static int	scsi_hba_get_eventcookie(
237			dev_info_t		*self,
238			dev_info_t		*child,
239			char			*name,
240			ddi_eventcookie_t	*eventp);
241
242static int	scsi_hba_add_eventcall(
243			dev_info_t		*self,
244			dev_info_t		*child,
245			ddi_eventcookie_t	event,
246			void			(*callback)(
247				dev_info_t		*dip,
248				ddi_eventcookie_t	event,
249				void			*arg,
250				void			*bus_impldata),
251			void			*arg,
252			ddi_callback_id_t	*cb_id);
253
254static int	scsi_hba_remove_eventcall(
255			dev_info_t		*self,
256			ddi_callback_id_t	id);
257
258static int	scsi_hba_post_event(
259			dev_info_t		*self,
260			dev_info_t		*child,
261			ddi_eventcookie_t	event,
262			void			*bus_impldata);
263
264static int	scsi_hba_bus_config(
265			dev_info_t		*self,
266			uint_t			flags,
267			ddi_bus_config_op_t	op,
268			void			*arg,
269			dev_info_t		**childp);
270
271static int	scsi_hba_bus_unconfig(
272			dev_info_t		*self,
273			uint_t			flags,
274			ddi_bus_config_op_t	op,
275			void			*arg);
276
277static int	scsi_hba_fm_init_child(
278			dev_info_t		*self,
279			dev_info_t		*child,
280			int			cap,
281			ddi_iblock_cookie_t	*ibc);
282
283static int	scsi_hba_bus_power(
284			dev_info_t		*self,
285			void			*impl_arg,
286			pm_bus_power_op_t	op,
287			void			*arg,
288			void			*result);
289
290/* bus_ops vector for SCSI HBA's. */
291static struct bus_ops scsi_hba_busops = {
292	BUSO_REV,
293	nullbusmap,			/* bus_map */
294	NULL,				/* bus_get_intrspec */
295	NULL,				/* bus_add_intrspec */
296	NULL,				/* bus_remove_intrspec */
297	scsi_hba_map_fault,		/* bus_map_fault */
298	NULL,				/* bus_dma_map */
299	ddi_dma_allochdl,		/* bus_dma_allochdl */
300	ddi_dma_freehdl,		/* bus_dma_freehdl */
301	ddi_dma_bindhdl,		/* bus_dma_bindhdl */
302	ddi_dma_unbindhdl,		/* bus_unbindhdl */
303	ddi_dma_flush,			/* bus_dma_flush */
304	ddi_dma_win,			/* bus_dma_win */
305	ddi_dma_mctl,			/* bus_dma_ctl */
306	scsi_hba_bus_ctl,		/* bus_ctl */
307	ddi_bus_prop_op,		/* bus_prop_op */
308	scsi_hba_get_eventcookie,	/* bus_get_eventcookie */
309	scsi_hba_add_eventcall,		/* bus_add_eventcall */
310	scsi_hba_remove_eventcall,	/* bus_remove_eventcall */
311	scsi_hba_post_event,		/* bus_post_event */
312	NULL,				/* bus_intr_ctl */
313	scsi_hba_bus_config,		/* bus_config */
314	scsi_hba_bus_unconfig,		/* bus_unconfig */
315	scsi_hba_fm_init_child,		/* bus_fm_init */
316	NULL,				/* bus_fm_fini */
317	NULL,				/* bus_fm_access_enter */
318	NULL,				/* bus_fm_access_exit */
319	scsi_hba_bus_power		/* bus_power */
320};
321
322/* cb_ops for hotplug :devctl and :scsi support */
323static struct cb_ops scsi_hba_cbops = {
324	scsi_hba_open,
325	scsi_hba_close,
326	nodev,			/* strategy */
327	nodev,			/* print */
328	nodev,			/* dump */
329	nodev,			/* read */
330	nodev,			/* write */
331	scsi_hba_ioctl,		/* ioctl */
332	nodev,			/* devmap */
333	nodev,			/* mmap */
334	nodev,			/* segmap */
335	nochpoll,		/* poll */
336	ddi_prop_op,		/* prop_op */
337	NULL,			/* stream */
338	D_NEW|D_MP|D_HOTPLUG,	/* cb_flag */
339	CB_REV,			/* rev */
340	nodev,			/* int (*cb_aread)() */
341	nodev			/* int (*cb_awrite)() */
342};
343
344/* Prototypes for static scsi_hba.c/SCSA private lunmap interfaces */
345static int	scsi_lunmap_create(
346			dev_info_t		*self,
347			impl_scsi_tgtmap_t	*tgtmap,
348			char			*tgt_addr);
349static void	scsi_lunmap_destroy(
350			dev_info_t		*self,
351			impl_scsi_tgtmap_t	*tgtmap,
352			char			*tgt_addr);
353static void	scsi_lunmap_set_begin(
354			dev_info_t		*self,
355			damap_t			*lundam);
356static int	scsi_lunmap_set_add(
357			dev_info_t		*self,
358			damap_t			*lundam,
359			char			*taddr,
360			scsi_lun64_t		lun_num,
361			int			lun_sfunc);
362static void	scsi_lunmap_set_end(
363			dev_info_t		*self,
364			damap_t			*lundam);
365
366/* Prototypes for static misc. scsi_hba.c private bus_config interfaces */
367static int scsi_hba_bus_config_iports(dev_info_t *self, uint_t flags,
368    ddi_bus_config_op_t op, void *arg, dev_info_t **childp);
369static int scsi_hba_bus_config_spi(dev_info_t *self, uint_t flags,
370    ddi_bus_config_op_t op, void *arg, dev_info_t **childp);
371static dev_info_t *scsi_hba_bus_config_port(dev_info_t *self,
372    char *nameaddr, scsi_enum_t se);
373
374#ifdef	sparc
375static int scsi_hba_bus_config_prom_node(dev_info_t *self, uint_t flags,
376    void *arg, dev_info_t **childp);
377#endif	/* sparc */
378
379
380/*
381 * SCSI_HBA_LOG is used for all messages. A logging level is specified when
382 * generating a message. Some levels correspond directly to cmn_err levels,
383 * some are associated with increasing levels diagnostic/debug output (LOG1-4),
384 * and others are associated with specific levels of interface (LOGMAP).
385 * For _LOG() messages, a __func__ prefix will identify the function origin
386 * of the message. For _LOG_NF messages, there is no function prefix or
387 * self/child context. Filtering of messages is provided based on logging
388 * level, but messages with cmn_err logging level and messages generated
389 * generated with _LOG_NF() are never filtered.
390 *
391 * For debugging, more complete information can be displayed with each message
392 * (full device path and pointer values) by adjusting scsi_hba_log_info.
393 */
394/* logging levels */
395#define	SCSI_HBA_LOGCONT	CE_CONT
396#define	SCSI_HBA_LOGNOTE	CE_NOTE
397#define	SCSI_HBA_LOGWARN	CE_WARN
398#define	SCSI_HBA_LOGPANIC	CE_PANIC
399#define	SCSI_HBA_LOGIGNORE	CE_IGNORE
400#define	SCSI_HBA_LOG_CE_MASK	0x0000000F	/* no filter for these levels */
401#define	SCSI_HBA_LOG1		0x00000010	/* DIAG1 level enable */
402#define	SCSI_HBA_LOG2		0x00000020	/* DIAG2 level enable */
403#define	SCSI_HBA_LOG3		0x00000040	/* DIAG3 level enable */
404#define	SCSI_HBA_LOG4		0x00000080	/* DIAG4 level enable */
405#define	SCSI_HBA_LOGMAPPHY	0x00000100	/* MAPPHY level enable */
406#define	SCSI_HBA_LOGMAPIPT	0x00000200	/* MAPIPT level enable */
407#define	SCSI_HBA_LOGMAPTGT	0x00000400	/* MAPTGT level enable */
408#define	SCSI_HBA_LOGMAPLUN	0x00000800	/* MAPLUN level enable */
409#define	SCSI_HBA_LOGMAPCFG	0x00001000	/* MAPCFG level enable */
410#define	SCSI_HBA_LOGMAPUNCFG	0x00002000	/* MAPUNCFG level enable */
411#define	SCSI_HBA_LOGTRACE	0x00010000	/* TRACE enable */
412#if (CE_CONT | CE_NOTE | CE_WARN | CE_PANIC | CE_IGNORE) > SCSI_HBA_LOG_CE_MASK
413Error, problem with CE_ definitions
414#endif
415
416/*
417 * Tunable log message augmentation and filters: filters do not apply to
418 * SCSI_HBA_LOG_CE_MASK level messages or LOG_NF() messages.
419 *
420 * An example set of /etc/system tunings to simplify debug a SCSA pHCI HBA
421 * driver called "pmcs", including "scsi_vhci" operation, by capturing
422 * log information in the system log might be:
423 *
424 * echo "set scsi:scsi_hba_log_filter_level=0x3ff0"		>> /etc/system
425 * echo "set scsi:scsi_hba_log_filter_phci=\"pmcs\""		>> /etc/system
426 * echo "set scsi:scsi_hba_log_filter_vhci=\"scsi_vhci\""	>> /etc/system
427 *
428 * To capture information on just HBA-SCSAv3 *map operation, use
429 * echo "set scsi:scsi_hba_log_filter_level=0x3f10"		>> /etc/system
430 *
431 * For debugging an HBA driver, you may also want to set:
432 *
433 * echo "set scsi:scsi_hba_log_align=1"				>> /etc/system
434 * echo "set scsi:scsi_hba_log_mt_disable=0x6"			>> /etc/system
435 * echo "set mtc_off=1"						>> /etc/system
436 * echo "set mdi_mtc_off=1"					>> /etc/system
437 * echo "set scsi:scsi_hba_log_fcif=0"				>> /etc/system
438 */
439int		scsi_hba_log_filter_level =
440			SCSI_HBA_LOG1 |
441			0;
442char		*scsi_hba_log_filter_phci = "\0\0\0\0\0\0\0\0\0\0\0\0";
443char		*scsi_hba_log_filter_vhci = "\0\0\0\0\0\0\0\0\0\0\0\0";
444int		scsi_hba_log_align = 0;	/* NOTE: will not cause truncation */
445int		scsi_hba_log_fcif = '!'; /* "^!?" first char in format */
446					/* NOTE: iff level > SCSI_HBA_LOG1 */
447					/* '\0'0x00 -> console and system log */
448					/* '^' 0x5e -> console_only */
449					/* '!' 0x21 -> system log only */
450					/* '?' 0x2F -> See cmn_err(9F) */
451int		scsi_hba_log_info =	/* augmentation: extra info output */
452			(0 << 0) |	/* 0x0001: process information */
453			(0 << 1) |	/* 0x0002: full /devices path */
454			(0 << 2);	/* 0x0004: devinfo pointer */
455
456int		scsi_hba_log_mt_disable =
457			/* SCSI_ENUMERATION_MT_LUN_DISABLE |	(ie 0x02) */
458			/* SCSI_ENUMERATION_MT_TARGET_DISABLE |	(ie 0x04) */
459			0;
460
461/* static data for HBA logging subsystem */
462static kmutex_t	scsi_hba_log_mutex;
463static char	scsi_hba_log_i[512];
464static char	scsi_hba_log_buf[512];
465static char	scsi_hba_fmt[512];
466
467/* Macros to use in scsi_hba.c source code below */
468#define	SCSI_HBA_LOG(x)	scsi_hba_log x
469#define	_LOG(level)	SCSI_HBA_LOG##level, __func__
470#define	_MAP(map)	SCSI_HBA_LOGMAP##map, __func__
471#define	_LOG_NF(level)	SCSI_HBA_LOG##level, NULL, NULL, NULL
472#define	_LOG_TRACE	_LOG(TRACE)
473#define	_LOGLUN		_MAP(LUN)
474#define	_LOGTGT		_MAP(TGT)
475#define	_LOGIPT		_MAP(IPT)
476#define	_LOGPHY		_MAP(PHY)
477#define	_LOGCFG		_MAP(CFG)
478#define	_LOGUNCFG	_MAP(UNCFG)
479
480/*PRINTFLIKE5*/
481static void
482scsi_hba_log(int level, const char *func, dev_info_t *self, dev_info_t *child,
483    const char *fmt, ...)
484{
485	va_list		ap;
486	int		clevel;
487	int		align;
488	char		*info;
489	char		*f;
490	char		*ua;
491
492	/* derive self from child's parent */
493	if ((self == NULL) && child)
494		self = ddi_get_parent(child);
495
496	/* no filtering of SCSI_HBA_LOG_CE_MASK or LOG_NF messages */
497	if (((level & SCSI_HBA_LOG_CE_MASK) != level) && (func != NULL)) {
498		/* scsi_hba_log_filter_level: filter on level as bitmask */
499		if ((level & scsi_hba_log_filter_level) == 0)
500			return;
501
502		/* scsi_hba_log_filter_phci/vhci: on name of driver */
503		if (*scsi_hba_log_filter_phci &&
504		    ((self == NULL) ||
505		    (ddi_driver_name(self) == NULL) ||
506		    strcmp(ddi_driver_name(self), scsi_hba_log_filter_phci))) {
507			/* does not match pHCI, check vHCI */
508			if (*scsi_hba_log_filter_vhci &&
509			    ((self == NULL) ||
510			    (ddi_driver_name(self) == NULL) ||
511			    strcmp(ddi_driver_name(self),
512			    scsi_hba_log_filter_vhci))) {
513				/* does not match vHCI */
514				return;
515			}
516		}
517
518
519		/* passed filters, determine align */
520		align = scsi_hba_log_align;
521
522		/* shorten func for filtered output */
523		if (strncmp(func, "scsi_hba_", 9) == 0)
524			func += 9;
525		if (strncmp(func, "scsi_", 5) == 0)
526			func += 5;
527	} else {
528		/* don't align output that is never filtered */
529		align = 0;
530	}
531
532	/* determine the cmn_err form from the level */
533	clevel = ((level & SCSI_HBA_LOG_CE_MASK) == level) ? level : CE_CONT;
534
535	/* protect common buffers used to format output */
536	mutex_enter(&scsi_hba_log_mutex);
537
538	/* skip special first characters, we add them back below */
539	f = (char *)fmt;
540	if (*f && strchr("^!?", *f))
541		f++;
542	va_start(ap, fmt);
543	(void) vsprintf(scsi_hba_log_buf, f, ap);
544	va_end(ap);
545
546	/* augment message with 'information' */
547	info = scsi_hba_log_i;
548	*info = '\0';
549	if ((scsi_hba_log_info & 0x0001) && curproc && PTOU(curproc)->u_comm) {
550		(void) sprintf(info, "%s[%d]%p ",
551		    PTOU(curproc)->u_comm, curproc->p_pid, (void *)curthread);
552		info += strlen(info);
553	}
554	if (self) {
555		if ((scsi_hba_log_info & 0x0004) && (child || self)) {
556			(void) sprintf(info, "%p ",
557			    (void *)(child ? child : self));
558			info += strlen(info);
559		}
560		if (scsi_hba_log_info & 0x0002)	{
561			(void) ddi_pathname(child ? child : self, info);
562			(void) strcat(info, " ");
563			info += strlen(info);
564		}
565
566		/* always provide 'default' information about self &child */
567		(void) sprintf(info, "%s%d ", ddi_driver_name(self),
568		    ddi_get_instance(self));
569		info += strlen(info);
570		if (child) {
571			ua = ddi_get_name_addr(child);
572			(void) sprintf(info, "%s@%s ",
573			    ddi_node_name(child), (ua && *ua) ? ua : "");
574			info += strlen(info);
575		}
576	}
577
578	/* turn off alignment if truncation would occur */
579	if (align && ((strlen(func) > 18) || (strlen(scsi_hba_log_i) > 36)))
580		align = 0;
581
582	/* adjust for aligned output */
583	if (align) {
584		if (func == NULL)
585			func = "";
586		/* remove trailing blank with align output */
587		if ((info != scsi_hba_log_i) && (*(info -1) == '\b'))
588			*(info - 1) = '\0';
589	}
590
591	/* special "first character in format" must be in format itself */
592	f = scsi_hba_fmt;
593	if (fmt[0] && strchr("^!?", fmt[0]))
594		*f++ = fmt[0];
595	else if (scsi_hba_log_fcif && (level > SCSI_HBA_LOG1))
596		*f++ = (char)scsi_hba_log_fcif;		/* add global fcif */
597	if (align)
598		(void) sprintf(f, "%s", "%-18.18s: %36.36s: %s%s");
599	else
600		(void) sprintf(f, "%s", func ? "%s: %s%s%s" : "%s%s%s");
601
602	if (func)
603		cmn_err(clevel, scsi_hba_fmt, func, scsi_hba_log_i,
604		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
605	else
606		cmn_err(clevel, scsi_hba_fmt, scsi_hba_log_i,
607		    scsi_hba_log_buf, clevel == CE_CONT ? "\n" : "");
608	mutex_exit(&scsi_hba_log_mutex);
609}
610
611int	scsi_enumeration_failed_panic = 0;
612int	scsi_enumeration_failed_hotplug = 1;
613
614static void
615scsi_enumeration_failed(dev_info_t *child, scsi_enum_t se,
616    char *arg, char *when)
617{
618	/* If 'se' is -1 the 'se' value comes from child. */
619	if (se == -1) {
620		ASSERT(child);
621		se = ndi_dev_is_hotplug_node(child) ? SE_HP : SE_BUSCONFIG;
622	}
623
624	if (scsi_enumeration_failed_panic) {
625		/* set scsi_enumeration_failed_panic to debug */
626		SCSI_HBA_LOG((_LOG(PANIC), NULL, child,
627		    "%s%senumeration failed during %s",
628		    arg ? arg : "", arg ? " " : "", when));
629	} else if (scsi_enumeration_failed_hotplug && (se == SE_HP)) {
630		/* set scsi_enumeration_failed_hotplug for console messages */
631		SCSI_HBA_LOG((_LOG(WARN), NULL, child,
632		    "%s%senumeration failed during %s",
633		    arg ? arg : "", arg ? " " : "", when));
634	} else {
635		/* default */
636		SCSI_HBA_LOG((_LOG(2), NULL, child,
637		    "%s%senumeration failed during %s",
638		    arg ? arg : "", arg ? " " : "", when));
639	}
640}
641
642/*
643 * scsi_hba version of [nm]di_devi_enter/[nm]di_devi_exit that detects if HBA
644 * is a PHCI, and chooses mdi/ndi locking implementation.
645 */
646static void
647scsi_hba_devi_enter(dev_info_t *self, int *circp)
648{
649	if (MDI_PHCI(self))
650		mdi_devi_enter(self, circp);
651	else
652		ndi_devi_enter(self, circp);
653}
654
655static int
656scsi_hba_devi_tryenter(dev_info_t *self, int *circp)
657{
658	if (MDI_PHCI(self))
659		return (mdi_devi_tryenter(self, circp));
660	else
661		return (ndi_devi_tryenter(self, circp));
662}
663
664static void
665scsi_hba_devi_exit(dev_info_t *self, int circ)
666{
667	if (MDI_PHCI(self))
668		mdi_devi_exit(self, circ);
669	else
670		ndi_devi_exit(self, circ);
671}
672
673static void
674scsi_hba_devi_enter_phci(dev_info_t *self, int *circp)
675{
676	if (MDI_PHCI(self))
677		mdi_devi_enter_phci(self, circp);
678}
679
680static void
681scsi_hba_devi_exit_phci(dev_info_t *self, int circ)
682{
683	if (MDI_PHCI(self))
684		mdi_devi_exit_phci(self, circ);
685}
686
687static int
688scsi_hba_dev_is_sid(dev_info_t *child)
689{
690	/*
691	 * Use ndi_dev_is_persistent_node instead of ddi_dev_is_sid to avoid
692	 * any possible locking issues in mixed nexus devctl code (like usb).
693	 */
694	return (ndi_dev_is_persistent_node(child));
695}
696
697/*
698 * Called from _init() when loading "scsi" module
699 */
700void
701scsi_initialize_hba_interface()
702{
703	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
704
705	/* We need "scsiprobe" and "scsinodev" as an alias or a driver. */
706	if (ddi_name_to_major(compatible_probe) == DDI_MAJOR_T_NONE) {
707		SCSI_HBA_LOG((_LOG_NF(WARN), "failed to resolve '%s' "
708		    "driver alias, defaulting to 'nulldriver'",
709		    compatible_probe));
710
711		/* If no "nulldriver" driver nothing will work... */
712		compatible_probe = "nulldriver";
713		if (ddi_name_to_major(compatible_probe) == DDI_MAJOR_T_NONE)
714			SCSI_HBA_LOG((_LOG_NF(WARN), "no probe '%s' driver, "
715			    "system misconfigured", compatible_probe));
716	}
717	if (ddi_name_to_major(compatible_nodev) == DDI_MAJOR_T_NONE) {
718		SCSI_HBA_LOG((_LOG_NF(WARN), "failed to resolve '%s' "
719		    "driver alias, defaulting to 'nulldriver'",
720		    compatible_nodev));
721
722		/* If no "nulldriver" driver nothing will work... */
723		compatible_nodev = "nulldriver";
724		if (ddi_name_to_major(compatible_nodev) == DDI_MAJOR_T_NONE)
725			SCSI_HBA_LOG((_LOG_NF(WARN), "no nodev '%s' driver, "
726			    "system misconfigured", compatible_nodev));
727	}
728
729	/*
730	 * Verify our special node name "probe" will not be used in other ways.
731	 * Don't expect things to work if they are.
732	 */
733	if (ddi_major_to_name(ddi_name_to_major("probe")))
734		SCSI_HBA_LOG((_LOG_NF(WARN),
735		    "driver already using special node name 'probe'"));
736
737	mutex_init(&scsi_log_mutex, NULL, MUTEX_DRIVER, NULL);
738	mutex_init(&scsi_flag_nointr_mutex, NULL, MUTEX_DRIVER, NULL);
739	cv_init(&scsi_flag_nointr_cv, NULL, CV_DRIVER, NULL);
740	mutex_init(&scsi_hba_log_mutex, NULL, MUTEX_DRIVER, NULL);
741
742	/* initialize the asynchronous barrier deletion daemon */
743	mutex_init(&scsi_hba_barrier_mutex, NULL, MUTEX_DRIVER, NULL);
744	cv_init(&scsi_hba_barrier_cv, NULL, CV_DRIVER, NULL);
745	(void) thread_create(NULL, 0,
746	    (void (*)())scsi_hba_barrier_daemon, NULL,
747	    0, &p0, TS_RUN, minclsyspri);
748
749	/* initialize lun change ASC/ASCQ processing daemon (stage1 & stage2) */
750	mutex_init(&scsi_lunchg1_mutex, NULL, MUTEX_DRIVER, NULL);
751	cv_init(&scsi_lunchg1_cv, NULL, CV_DRIVER, NULL);
752	(void) thread_create(NULL, 0,
753	    (void (*)())scsi_lunchg1_daemon, NULL,
754	    0, &p0, TS_RUN, minclsyspri);
755	mutex_init(&scsi_lunchg2_mutex, NULL, MUTEX_DRIVER, NULL);
756	cv_init(&scsi_lunchg2_cv, NULL, CV_DRIVER, NULL);
757	(void) thread_create(NULL, 0,
758	    (void (*)())scsi_lunchg2_daemon, NULL,
759	    0, &p0, TS_RUN, minclsyspri);
760}
761
762int
763scsi_hba_pkt_constructor(void *buf, void *arg, int kmflag)
764{
765	struct scsi_pkt_cache_wrapper *pktw;
766	struct scsi_pkt		*pkt;
767	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
768	int			pkt_len;
769	char			*ptr;
770
771	/*
772	 * allocate a chunk of memory for the following:
773	 * scsi_pkt
774	 * pcw_* fields
775	 * pkt_ha_private
776	 * pkt_cdbp, if needed
777	 * (pkt_private always null)
778	 * pkt_scbp, if needed
779	 */
780	pkt_len = tran->tran_hba_len + sizeof (struct scsi_pkt_cache_wrapper);
781	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB)
782		pkt_len += DEFAULT_CDBLEN;
783	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
784		pkt_len += DEFAULT_SCBLEN;
785	bzero(buf, pkt_len);
786
787	ptr = buf;
788	pktw = buf;
789	ptr += sizeof (struct scsi_pkt_cache_wrapper);
790	pkt = &(pktw->pcw_pkt);
791	pkt->pkt_ha_private = (opaque_t)ptr;
792
793	pktw->pcw_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
794	/*
795	 * keep track of the granularity at the time this handle was
796	 * allocated
797	 */
798	pktw->pcw_granular = tran->tran_dma_attr.dma_attr_granular;
799
800	if (ddi_dma_alloc_handle(tran->tran_hba_dip, &tran->tran_dma_attr,
801	    kmflag == KM_SLEEP ? SLEEP_FUNC: NULL_FUNC, NULL,
802	    &pkt->pkt_handle) != DDI_SUCCESS) {
803
804		return (-1);
805	}
806	ptr += tran->tran_hba_len;
807	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) {
808		pkt->pkt_cdbp = (opaque_t)ptr;
809		ptr += DEFAULT_CDBLEN;
810	}
811	pkt->pkt_private = NULL;
812	if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
813		pkt->pkt_scbp = (opaque_t)ptr;
814	if (tran->tran_pkt_constructor)
815		return ((*tran->tran_pkt_constructor)(pkt, arg, kmflag));
816	else
817		return (0);
818}
819
820#define	P_TO_TRAN(pkt)	((pkt)->pkt_address.a_hba_tran)
821
822void
823scsi_hba_pkt_destructor(void *buf, void *arg)
824{
825	struct scsi_pkt_cache_wrapper *pktw = buf;
826	struct scsi_pkt		*pkt = &(pktw->pcw_pkt);
827	scsi_hba_tran_t		*tran = (scsi_hba_tran_t *)arg;
828
829	ASSERT(pktw->pcw_magic == PKT_WRAPPER_MAGIC);
830	ASSERT((pktw->pcw_flags & PCW_BOUND) == 0);
831	if (tran->tran_pkt_destructor)
832		(*tran->tran_pkt_destructor)(pkt, arg);
833
834	/* make sure nobody messed with our pointers */
835	ASSERT(pkt->pkt_ha_private == (opaque_t)((char *)pkt +
836	    sizeof (struct scsi_pkt_cache_wrapper)));
837	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_SCB) == 0) ||
838	    (pkt->pkt_scbp == (opaque_t)((char *)pkt +
839	    tran->tran_hba_len +
840	    (((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ?
841	    0 : DEFAULT_CDBLEN) +
842	    DEFAULT_PRIVLEN + sizeof (struct scsi_pkt_cache_wrapper))));
843	ASSERT(((tran->tran_hba_flags & SCSI_HBA_TRAN_CDB) == 0) ||
844	    (pkt->pkt_cdbp == (opaque_t)((char *)pkt +
845	    tran->tran_hba_len +
846	    sizeof (struct scsi_pkt_cache_wrapper))));
847	ASSERT(pkt->pkt_handle);
848	ddi_dma_free_handle(&pkt->pkt_handle);
849	pkt->pkt_handle = NULL;
850	pkt->pkt_numcookies = 0;
851	pktw->pcw_total_xfer = 0;
852	pktw->pcw_totalwin = 0;
853	pktw->pcw_curwin = 0;
854}
855
856/*
857 * Called by an HBA from _init() to plumb in common SCSA bus_ops and
858 * cb_ops for the HBA's :devctl and :scsi minor nodes.
859 */
860int
861scsi_hba_init(struct modlinkage *modlp)
862{
863	struct dev_ops *hba_dev_ops;
864
865	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
866
867	/*
868	 * Get a pointer to the dev_ops structure of the HBA and plumb our
869	 * bus_ops vector into the HBA's dev_ops structure.
870	 */
871	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
872	ASSERT(hba_dev_ops->devo_bus_ops == NULL);
873	hba_dev_ops->devo_bus_ops = &scsi_hba_busops;
874
875	/*
876	 * Plumb our cb_ops vector into the HBA's dev_ops structure to
877	 * provide getinfo and hotplugging ioctl support if the HBA driver
878	 * does not already provide this support.
879	 */
880	if (hba_dev_ops->devo_cb_ops == NULL) {
881		hba_dev_ops->devo_cb_ops = &scsi_hba_cbops;
882	}
883	if (hba_dev_ops->devo_cb_ops->cb_open == scsi_hba_open) {
884		ASSERT(hba_dev_ops->devo_cb_ops->cb_close == scsi_hba_close);
885		hba_dev_ops->devo_getinfo = scsi_hba_info;
886	}
887	return (0);
888}
889
890/*
891 * Called by an HBA attach(9E) to allocate a scsi_hba_tran(9S) structure. An
892 * HBA driver will then initialize the structure and then call
893 * scsi_hba_attach_setup(9F).
894 */
895/*ARGSUSED*/
896scsi_hba_tran_t *
897scsi_hba_tran_alloc(
898	dev_info_t		*self,
899	int			flags)
900{
901	scsi_hba_tran_t		*tran;
902
903	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
904
905	/* allocate SCSA flavors for self */
906	ndi_flavorv_alloc(self, SCSA_NFLAVORS);
907
908	tran = kmem_zalloc(sizeof (scsi_hba_tran_t),
909	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
910
911	if (tran) {
912		tran->tran_interconnect_type = INTERCONNECT_PARALLEL;
913
914		/*
915		 * HBA driver called scsi_hba_tran_alloc(), so tran structure
916		 * is proper size and unused/newer fields are zero.
917		 *
918		 * NOTE: We use SCSA_HBA_SCSA_TA as an obtuse form of
919		 * versioning to detect old HBA drivers that do not use
920		 * scsi_hba_tran_alloc, and would present garbage data
921		 * (instead of valid/zero data) for newer tran fields.
922		 */
923		tran->tran_hba_flags |= SCSI_HBA_SCSA_TA;
924	}
925
926	return (tran);
927}
928
929/*
930 * Called by an HBA to free a scsi_hba_tran structure
931 */
932void
933scsi_hba_tran_free(
934	scsi_hba_tran_t		*tran)
935{
936	SCSI_HBA_LOG((_LOG_TRACE, tran->tran_hba_dip, NULL, __func__));
937
938	kmem_free(tran, sizeof (scsi_hba_tran_t));
939}
940
941int
942scsi_tran_ext_alloc(
943	scsi_hba_tran_t		*tran,
944	size_t			length,
945	int			flags)
946{
947	void	*tran_ext;
948	int	ret = DDI_FAILURE;
949
950	tran_ext = kmem_zalloc(length,
951	    (flags & SCSI_HBA_CANSLEEP) ? KM_SLEEP : KM_NOSLEEP);
952	if (tran_ext != NULL) {
953		tran->tran_extension = tran_ext;
954		ret = DDI_SUCCESS;
955	}
956	return (ret);
957}
958
959void
960scsi_tran_ext_free(
961	scsi_hba_tran_t		*tran,
962	size_t			length)
963{
964	if (tran->tran_extension != NULL) {
965		kmem_free(tran->tran_extension, length);
966		tran->tran_extension = NULL;
967	}
968}
969
970/*
971 * Common nexus teardown code: used by both scsi_hba_detach() on SCSA HBA node
972 * and iport_postdetach_tran_scsi_device() on a SCSA HBA iport node (and for
973 * failure cleanup). Undo scsa_nexus_setup in reverse order.
974 *
975 * NOTE: Since we are in the Solaris IO framework, we can depend on
976 * undocumented cleanup operations performed by other parts of the framework:
977 * like detach_node() calling ddi_prop_remove_all() and
978 * ddi_remove_minor_node(,NULL).
979 */
980static void
981scsa_nexus_teardown(dev_info_t *self, scsi_hba_tran_t	*tran)
982{
983	/* Teardown FMA. */
984	if (tran->tran_hba_flags & SCSI_HBA_SCSA_FM) {
985		ddi_fm_fini(self);
986		tran->tran_hba_flags &= ~SCSI_HBA_SCSA_FM;
987	}
988}
989
990/*
991 * Common nexus setup code: used by both scsi_hba_attach_setup() on SCSA HBA
992 * node and iport_preattach_tran_scsi_device() on a SCSA HBA iport node.
993 *
994 * This code makes no assumptions about tran use by scsi_device children.
995 */
996static int
997scsa_nexus_setup(dev_info_t *self, scsi_hba_tran_t *tran)
998{
999	int		capable;
1000	int		scsa_minor;
1001
1002	/*
1003	 * NOTE: SCSA maintains an 'fm-capable' domain, in tran_fm_capable,
1004	 * that is not dependent (limited by) the capabilities of its parents.
1005	 * For example a devinfo node in a branch that is not
1006	 * DDI_FM_EREPORT_CAPABLE may report as capable, via tran_fm_capable,
1007	 * to its scsi_device children.
1008	 *
1009	 * Get 'fm-capable' property from driver.conf, if present. If not
1010	 * present, default to the scsi_fm_capable global (which has
1011	 * DDI_FM_EREPORT_CAPABLE set by default).
1012	 */
1013	if (tran->tran_fm_capable == DDI_FM_NOT_CAPABLE)
1014		tran->tran_fm_capable = ddi_prop_get_int(DDI_DEV_T_ANY, self,
1015		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1016		    "fm-capable", scsi_fm_capable);
1017
1018	/*
1019	 * If an HBA is *not* doing its own fma support by calling
1020	 * ddi_fm_init() prior to scsi_hba_attach_setup(), we provide a minimal
1021	 * common SCSA implementation so that scsi_device children can generate
1022	 * ereports via scsi_fm_ereport_post().  We use ddi_fm_capable() to
1023	 * detect an HBA calling ddi_fm_init() prior to scsi_hba_attach_setup().
1024	 */
1025	if (tran->tran_fm_capable &&
1026	    (ddi_fm_capable(self) == DDI_FM_NOT_CAPABLE)) {
1027		/*
1028		 * We are capable of something, pass our capabilities up the
1029		 * tree, but use a local variable so our parent can't limit
1030		 * our capabilities (we don't want our parent to clear
1031		 * DDI_FM_EREPORT_CAPABLE).
1032		 *
1033		 * NOTE: iblock cookies are not important because scsi HBAs
1034		 * always interrupt below LOCK_LEVEL.
1035		 */
1036		capable = tran->tran_fm_capable;
1037		ddi_fm_init(self, &capable, NULL);
1038
1039		/*
1040		 * Set SCSI_HBA_SCSA_FM bit to mark us as using the common
1041		 * minimal SCSA fm implementation -  we called ddi_fm_init(),
1042		 * so we are responsible for calling ddi_fm_fini() in
1043		 * scsi_hba_detach().
1044		 *
1045		 * NOTE: if ddi_fm_init fails to establish handle, SKIP cleanup.
1046		 */
1047		if (DEVI(self)->devi_fmhdl)
1048			tran->tran_hba_flags |= SCSI_HBA_SCSA_FM;
1049	}
1050
1051	/* If SCSA responsible for for minor nodes, create :devctl minor. */
1052	scsa_minor = (ddi_get_driver(self)->devo_cb_ops->cb_open ==
1053	    scsi_hba_open) ? 1 : 0;
1054	if (scsa_minor && ((ddi_create_minor_node(self, "devctl", S_IFCHR,
1055	    INST2DEVCTL(ddi_get_instance(self)), DDI_NT_SCSI_NEXUS, 0) !=
1056	    DDI_SUCCESS))) {
1057		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1058		    "can't create :devctl minor node"));
1059		goto fail;
1060	}
1061
1062	return (DDI_SUCCESS);
1063
1064fail:	scsa_nexus_teardown(self, tran);
1065	return (DDI_FAILURE);
1066}
1067
1068/*
1069 * Common tran teardown code: used by iport_postdetach_tran_scsi_device() on a
1070 * SCSA HBA iport node and (possibly) by scsi_hba_detach() on SCSA HBA node
1071 * (and for failure cleanup). Undo scsa_tran_setup in reverse order.
1072 *
1073 * NOTE: Since we are in the Solaris IO framework, we can depend on
1074 * undocumented cleanup operations performed by other parts of the framework:
1075 * like detach_node() calling ddi_prop_remove_all() and
1076 * ddi_remove_minor_node(,NULL).
1077 */
1078static void
1079scsa_tran_teardown(dev_info_t *self, scsi_hba_tran_t *tran)
1080{
1081	tran->tran_iport_dip = NULL;
1082
1083	/* Teardown pHCI registration */
1084	if (tran->tran_hba_flags & SCSI_HBA_SCSA_PHCI) {
1085		(void) mdi_phci_unregister(self, 0);
1086		tran->tran_hba_flags &= ~SCSI_HBA_SCSA_PHCI;
1087	}
1088}
1089
1090/*
1091 * Common tran setup code: used by iport_preattach_tran_scsi_device() on a
1092 * SCSA HBA iport node and (possibly) by scsi_hba_attach_setup() on SCSA HBA
1093 * node.
1094 */
1095static int
1096scsa_tran_setup(dev_info_t *self, scsi_hba_tran_t *tran)
1097{
1098	int			scsa_minor;
1099	int			id;
1100	char			*scsi_binding_set;
1101	static const char	*interconnect[] = INTERCONNECT_TYPE_ASCII;
1102
1103	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
1104
1105	/* If SCSA responsible for for minor nodes, create ":scsi" */
1106	scsa_minor = (ddi_get_driver(self)->devo_cb_ops->cb_open ==
1107	    scsi_hba_open) ? 1 : 0;
1108	if (scsa_minor && (ddi_create_minor_node(self, "scsi", S_IFCHR,
1109	    INST2SCSI(ddi_get_instance(self)),
1110	    DDI_NT_SCSI_ATTACHMENT_POINT, 0) != DDI_SUCCESS)) {
1111		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1112		    "can't create :scsi minor node"));
1113		goto fail;
1114	}
1115
1116	/*
1117	 * If the property does not already exist on self then see if we can
1118	 * pull it from further up the tree and define it on self. If the
1119	 * property does not exist above (including options.conf) then use the
1120	 * default value specified (global variable). We pull things down from
1121	 * above for faster "DDI_PROP_NOTPROM | DDI_PROP_DONTPASS" runtime
1122	 * access.
1123	 *
1124	 * Future: Should we avoid creating properties when value == global?
1125	 */
1126#define	CONFIG_INT_PROP(s, p, dv)	{			\
1127	if ((ddi_prop_exists(DDI_DEV_T_ANY, s,			\
1128	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, p) == 0) &&	\
1129	    (ndi_prop_update_int(DDI_DEV_T_NONE, s, p,		\
1130	    ddi_prop_get_int(DDI_DEV_T_ANY, ddi_get_parent(s),	\
1131	    DDI_PROP_NOTPROM, p, dv)) != DDI_PROP_SUCCESS))	\
1132		SCSI_HBA_LOG((_LOG(WARN), NULL, s,		\
1133		    "can't create property '%s'", p));		\
1134	}
1135
1136	/* Decorate with scsi configuration properties */
1137	CONFIG_INT_PROP(self, "scsi-enumeration", scsi_enumeration);
1138	CONFIG_INT_PROP(self, "scsi-options", scsi_options);
1139	CONFIG_INT_PROP(self, "scsi-reset-delay", scsi_reset_delay);
1140	CONFIG_INT_PROP(self, "scsi-watchdog-tick", scsi_watchdog_tick);
1141	CONFIG_INT_PROP(self, "scsi-selection-timeout", scsi_selection_timeout);
1142	CONFIG_INT_PROP(self, "scsi-tag-age-limit", scsi_tag_age_limit);
1143
1144	/*
1145	 * Pull down the scsi-initiator-id from further up the tree, or as
1146	 * defined by OBP. Place on node for faster access. NOTE: there is
1147	 * some confusion about what the name of the property should be.
1148	 */
1149	id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0, "initiator-id", -1);
1150	if (id == -1)
1151		id = ddi_prop_get_int(DDI_DEV_T_ANY, self, 0,
1152		    "scsi-initiator-id", -1);
1153	if (id != -1)
1154		CONFIG_INT_PROP(self, "scsi-initiator-id", id);
1155
1156	/*
1157	 * If we are responsible for tran allocation, establish
1158	 * 'initiator-interconnect-type'.
1159	 */
1160	if ((tran->tran_hba_flags & SCSI_HBA_SCSA_TA) &&
1161	    (tran->tran_interconnect_type > 0) &&
1162	    (tran->tran_interconnect_type < INTERCONNECT_MAX)) {
1163		if (ndi_prop_update_string(DDI_DEV_T_NONE, self,
1164		    "initiator-interconnect-type",
1165		    (char *)interconnect[tran->tran_interconnect_type])
1166		    != DDI_PROP_SUCCESS) {
1167			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1168			    "failed to establish "
1169			    "'initiator-interconnect-type'"));
1170			goto fail;
1171		}
1172	}
1173
1174	/*
1175	 * The 'scsi-binding-set' property can be defined in driver.conf
1176	 * files of legacy drivers on an as-needed basis. If 'scsi-binding-set'
1177	 * is not driver.conf defined, and the HBA is not implementing its own
1178	 * private bus_config, we define scsi-binding-set to the default
1179	 * 'spi' legacy value.
1180	 *
1181	 * NOTE: This default 'spi' value will be deleted if an HBA driver
1182	 * ends up using the scsi_hba_tgtmap_create() enumeration services.
1183	 *
1184	 * NOTE: If we were ever to decide to derive 'scsi-binding-set' from
1185	 * the IEEE-1275 'device_type' property then this is where that code
1186	 * should go - there is not enough consistency in 'device_type' to do
1187	 * this correctly at this point in time.
1188	 */
1189	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
1190	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "scsi-binding-set",
1191	    &scsi_binding_set) == DDI_PROP_SUCCESS) {
1192		SCSI_HBA_LOG((_LOG(2), NULL, self,
1193		    "external 'scsi-binding-set' \"%s\"", scsi_binding_set));
1194		ddi_prop_free(scsi_binding_set);
1195	} else if (scsi_binding_set_spi &&
1196	    ((tran->tran_bus_config == NULL) ||
1197	    (tran->tran_bus_config == scsi_hba_bus_config_spi))) {
1198		if (ndi_prop_update_string(DDI_DEV_T_NONE, self,
1199		    "scsi-binding-set", scsi_binding_set_spi) !=
1200		    DDI_PROP_SUCCESS) {
1201			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1202			    "failed to establish 'scsi_binding_set' default"));
1203			goto fail;
1204		}
1205		SCSI_HBA_LOG((_LOG(2), NULL, self,
1206		    "default 'scsi-binding-set' \"%s\"", scsi_binding_set_spi));
1207	} else
1208		SCSI_HBA_LOG((_LOG(2), NULL, self,
1209		    "no 'scsi-binding-set'"));
1210
1211	/*
1212	 * If SCSI_HBA_TRAN_PHCI is set, take care of pHCI registration of the
1213	 * initiator.
1214	 */
1215	if ((tran->tran_hba_flags & SCSI_HBA_TRAN_PHCI) &&
1216	    (mdi_phci_register(MDI_HCI_CLASS_SCSI, self, 0) == MDI_SUCCESS))
1217		tran->tran_hba_flags |= SCSI_HBA_SCSA_PHCI;
1218
1219	/* NOTE: tran_hba_dip is for DMA operation at the HBA node level */
1220	tran->tran_iport_dip = self;		/* for iport association */
1221	return (DDI_SUCCESS);
1222
1223fail:	scsa_tran_teardown(self, tran);
1224	return (DDI_FAILURE);
1225}
1226
1227/*
1228 * Called by a SCSA HBA driver to attach an instance of the driver to
1229 * SCSA HBA node  enumerated by PCI.
1230 */
1231int
1232scsi_hba_attach_setup(
1233	dev_info_t		*self,
1234	ddi_dma_attr_t		*hba_dma_attr,
1235	scsi_hba_tran_t		*tran,
1236	int			flags)
1237{
1238	int			len;
1239	char			cache_name[96];
1240
1241	SCSI_HBA_LOG((_LOG_TRACE, self, NULL, __func__));
1242
1243	/*
1244	 * Verify that we are a driver so other code does not need to
1245	 * check for NULL ddi_get_driver() result.
1246	 */
1247	if (ddi_get_driver(self) == NULL)
1248		return (DDI_FAILURE);
1249
1250	/*
1251	 * Verify that we are called on a SCSA HBA node (function enumerated
1252	 * by PCI), not on an iport node.
1253	 */
1254	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1255	if (scsi_hba_iport_unit_address(self))
1256		return (DDI_FAILURE);		/* self can't be an iport */
1257
1258	/* Caller must provide the tran. */
1259	ASSERT(tran);
1260	if (tran == NULL)
1261		return (DDI_FAILURE);
1262
1263	/*
1264	 * Verify correct scsi_hba_tran_t form:
1265	 *
1266	 * o Both or none of tran_get_name/tran_get_addr.
1267	 *   NOTE: Older  SCSA HBA drivers for SCSI transports with addressing
1268	 *   that did not fit the SPI "struct scsi_address" model were required
1269	 *   to implement tran_get_name and tran_get_addr. This is no longer
1270	 *   true - modern transport drivers should now use common SCSA
1271	 *   enumeration services.  The SCSA enumeration code will represent
1272	 *   the unit-address using well-known address properties
1273	 *   (SCSI_ADDR_PROP_TARGET_PORT, SCSI_ADDR_PROP_LUN64) during
1274	 *   devinfo/pathinfo node creation. The HBA driver can obtain values
1275	 *   using scsi_device_prop_lookup_*() from its tran_tgt_init(9E).
1276	 *
1277	 */
1278	if ((tran->tran_get_name == NULL) ^ (tran->tran_get_bus_addr == NULL)) {
1279		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
1280		    "should support both or neither: "
1281		    "tran_get_name, tran_get_bus_addr"));
1282		return (DDI_FAILURE);
1283	}
1284
1285	/*
1286	 * Establish the devinfo context of this tran structure, preserving
1287	 * knowledge of how the tran was allocated.
1288	 */
1289	tran->tran_hba_dip = self;		/* for DMA */
1290	tran->tran_hba_flags = (flags & ~SCSI_HBA_SCSA_TA) |
1291	    (tran->tran_hba_flags & SCSI_HBA_SCSA_TA);
1292
1293	/* Establish flavor of transport (and ddi_get_driver_private()) */
1294	ndi_flavorv_set(self, SCSA_FLAVOR_SCSI_DEVICE, tran);
1295
1296	/*
1297	 * Note: We only need dma_attr_minxfer and dma_attr_burstsizes
1298	 * from the DMA attributes. scsi_hba_attach(9f) only guarantees
1299	 * that these two fields are initialized properly. If this
1300	 * changes, be sure to revisit the implementation of
1301	 * scsi_hba_attach(9F).
1302	 */
1303	(void) memcpy(&tran->tran_dma_attr, hba_dma_attr,
1304	    sizeof (ddi_dma_attr_t));
1305
1306	/* Create tran_setup_pkt(9E) kmem_cache. */
1307	if (tran->tran_setup_pkt) {
1308		ASSERT(tran->tran_init_pkt == NULL);
1309		ASSERT(tran->tran_destroy_pkt == NULL);
1310		if (tran->tran_init_pkt || tran->tran_destroy_pkt)
1311			goto fail;
1312
1313		tran->tran_init_pkt = scsi_init_cache_pkt;
1314		tran->tran_destroy_pkt = scsi_free_cache_pkt;
1315		tran->tran_sync_pkt = scsi_sync_cache_pkt;
1316		tran->tran_dmafree = scsi_cache_dmafree;
1317
1318		len = sizeof (struct scsi_pkt_cache_wrapper);
1319		len += ROUNDUP(tran->tran_hba_len);
1320		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CDB)
1321			len += ROUNDUP(DEFAULT_CDBLEN);
1322		if (tran->tran_hba_flags & SCSI_HBA_TRAN_SCB)
1323			len += ROUNDUP(DEFAULT_SCBLEN);
1324
1325		(void) snprintf(cache_name, sizeof (cache_name),
1326		    "pkt_cache_%s_%d", ddi_driver_name(self),
1327		    ddi_get_instance(self));
1328
1329		tran->tran_pkt_cache_ptr = kmem_cache_create(
1330		    cache_name, len, 8, scsi_hba_pkt_constructor,
1331		    scsi_hba_pkt_destructor, NULL, tran, NULL, 0);
1332	}
1333
1334	/* Perform node setup independent of initiator role */
1335	if (scsa_nexus_setup(self, tran) != DDI_SUCCESS)
1336		goto fail;
1337
1338	/*
1339	 * The SCSI_HBA_HBA flag is passed to scsi_hba_attach_setup when the
1340	 * HBA driver knows that *all* children of the SCSA HBA node will be
1341	 * 'iports'. If the SCSA HBA node can have iport children and also
1342	 * function as an initiator for xxx_device children then it should
1343	 * not specify SCSI_HBA_HBA in its scsi_hba_attach_setup call. An
1344	 * HBA driver that does not manage iports should not set SCSA_HBA_HBA.
1345	 */
1346	if (tran->tran_hba_flags & SCSI_HBA_HBA) {
1347		/*
1348		 * Set the 'ddi-config-driver-node' property on the nexus
1349		 * node that notify attach_driver_nodes() to configure all
1350		 * immediate children so that nodes which bind to the
1351		 * same driver as parent are able to be added into per-driver
1352		 * list.
1353		 */
1354		if (ndi_prop_create_boolean(DDI_DEV_T_NONE,
1355		    self, "ddi-config-driver-node") != DDI_PROP_SUCCESS)
1356			goto fail;
1357	} else {
1358		if (scsa_tran_setup(self, tran) != DDI_SUCCESS)
1359			goto fail;
1360	}
1361
1362	return (DDI_SUCCESS);
1363
1364fail:	(void) scsi_hba_detach(self);
1365	return (DDI_FAILURE);
1366}
1367
1368/*
1369 * Called by an HBA to detach an instance of the driver. This may be called
1370 * for SCSA HBA nodes and for SCSA iport nodes.
1371 */
1372int
1373scsi_hba_detach(dev_info_t *self)
1374{
1375	scsi_hba_tran_t		*tran;
1376
1377	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1378	if (scsi_hba_iport_unit_address(self))
1379		return (DDI_FAILURE);		/* self can't be an iport */
1380
1381	/* Check all error return conditions upfront */
1382	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1383	ASSERT(tran);
1384	if (tran == NULL)
1385		return (DDI_FAILURE);
1386
1387	ASSERT(tran->tran_open_flag == 0);
1388	if (tran->tran_open_flag)
1389		return (DDI_FAILURE);
1390
1391	if (!(tran->tran_hba_flags & SCSI_HBA_HBA))
1392		scsa_tran_teardown(self, tran);
1393	scsa_nexus_teardown(self, tran);
1394
1395	/* Teardown tran_setup_pkt(9E) kmem_cache. */
1396	if (tran->tran_pkt_cache_ptr) {
1397		kmem_cache_destroy(tran->tran_pkt_cache_ptr);
1398		tran->tran_pkt_cache_ptr = NULL;
1399	}
1400
1401	(void) memset(&tran->tran_dma_attr, 0, sizeof (ddi_dma_attr_t));
1402
1403	/* Teardown flavor of transport (and ddi_get_driver_private()) */
1404	ndi_flavorv_set(self, SCSA_FLAVOR_SCSI_DEVICE, NULL);
1405
1406	tran->tran_hba_dip = NULL;
1407
1408	return (DDI_SUCCESS);
1409}
1410
1411
1412/*
1413 * Called by an HBA from _fini()
1414 */
1415void
1416scsi_hba_fini(struct modlinkage *modlp)
1417{
1418	struct dev_ops *hba_dev_ops;
1419
1420	SCSI_HBA_LOG((_LOG_TRACE, NULL, NULL, __func__));
1421
1422	/* Get the devops structure of this module and clear bus_ops vector. */
1423	hba_dev_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
1424
1425	if (hba_dev_ops->devo_cb_ops == &scsi_hba_cbops)
1426		hba_dev_ops->devo_cb_ops = NULL;
1427
1428	if (hba_dev_ops->devo_getinfo == scsi_hba_info)
1429		hba_dev_ops->devo_getinfo = NULL;
1430
1431	hba_dev_ops->devo_bus_ops = (struct bus_ops *)NULL;
1432}
1433
1434/*
1435 * SAS specific functions
1436 */
1437smp_hba_tran_t *
1438smp_hba_tran_alloc(dev_info_t *self)
1439{
1440	/* allocate SCSA flavors for self */
1441	ndi_flavorv_alloc(self, SCSA_NFLAVORS);
1442	return (kmem_zalloc(sizeof (smp_hba_tran_t), KM_SLEEP));
1443}
1444
1445void
1446smp_hba_tran_free(smp_hba_tran_t *tran)
1447{
1448	kmem_free(tran, sizeof (smp_hba_tran_t));
1449}
1450
1451int
1452smp_hba_attach_setup(
1453	dev_info_t		*self,
1454	smp_hba_tran_t		*tran)
1455{
1456	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1457	if (scsi_hba_iport_unit_address(self))
1458		return (DDI_FAILURE);		/* self can't be an iport */
1459
1460	/*
1461	 * The owner of the this devinfo_t was responsible
1462	 * for informing the framework already about
1463	 * additional flavors.
1464	 */
1465	ndi_flavorv_set(self, SCSA_FLAVOR_SMP, tran);
1466	return (DDI_SUCCESS);
1467}
1468
1469int
1470smp_hba_detach(dev_info_t *self)
1471{
1472	ASSERT(scsi_hba_iport_unit_address(self) == NULL);
1473	if (scsi_hba_iport_unit_address(self))
1474		return (DDI_FAILURE);		/* self can't be an iport */
1475
1476	ndi_flavorv_set(self, SCSA_FLAVOR_SMP, NULL);
1477	return (DDI_SUCCESS);
1478}
1479
1480/*
1481 * SMP child flavored functions
1482 */
1483static int
1484smp_busctl_ua(dev_info_t *child, char *addr, int maxlen)
1485{
1486	char		*tport;
1487	char		*wwn;
1488
1489	/* limit ndi_devi_findchild_by_callback to expected flavor */
1490	if (ndi_flavor_get(child) != SCSA_FLAVOR_SMP)
1491		return (DDI_FAILURE);
1492
1493	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1494	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1495	    SCSI_ADDR_PROP_TARGET_PORT, &tport) == DDI_SUCCESS) {
1496		(void) snprintf(addr, maxlen, "%s", tport);
1497		ddi_prop_free(tport);
1498		return (DDI_SUCCESS);
1499	}
1500
1501	/*
1502	 * NOTE: the following code should be deleted when mpt is changed to
1503	 * use SCSI_ADDR_PROP_TARGET_PORT instead of SMP_WWN.
1504	 */
1505	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1506	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1507	    SMP_WWN, &wwn) == DDI_SUCCESS) {
1508		(void) snprintf(addr, maxlen, "w%s", wwn);
1509		ddi_prop_free(wwn);
1510		return (DDI_SUCCESS);
1511	}
1512	return (DDI_FAILURE);
1513}
1514
1515static int
1516smp_busctl_reportdev(dev_info_t *child)
1517{
1518	dev_info_t	*self = ddi_get_parent(child);
1519	char		*tport;
1520	char		*wwn;
1521
1522	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1523	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1524	    SCSI_ADDR_PROP_TARGET_PORT, &tport) == DDI_SUCCESS) {
1525		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: target-port %s",
1526		    ddi_driver_name(child), ddi_get_instance(child),
1527		    ddi_driver_name(self), ddi_get_instance(self), tport));
1528		ddi_prop_free(tport);
1529		return (DDI_SUCCESS);
1530	}
1531
1532	/*
1533	 * NOTE: the following code should be deleted when mpt is changed to
1534	 * use SCSI_ADDR_PROP_TARGET_PORT instead of SMP_WWN.
1535	 */
1536	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
1537	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1538	    SMP_WWN, &wwn) == DDI_SUCCESS) {
1539		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: wwn %s",
1540		    ddi_driver_name(child), ddi_get_instance(child),
1541		    ddi_driver_name(self), ddi_get_instance(self), wwn));
1542		ddi_prop_free(wwn);
1543		return (DDI_SUCCESS);
1544	}
1545	return (DDI_FAILURE);
1546}
1547
1548static int
1549smp_busctl_initchild(dev_info_t *child)
1550{
1551	dev_info_t		*self = ddi_get_parent(child);
1552	smp_hba_tran_t		*tran;
1553	dev_info_t		*dup;
1554	char			addr[SCSI_MAXNAMELEN];
1555	struct smp_device	*smp_sd;
1556	uint64_t		wwn;
1557
1558	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SMP);
1559	ASSERT(tran);
1560	if (tran == NULL)
1561		return (DDI_FAILURE);
1562
1563	if (smp_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS)
1564		return (DDI_NOT_WELL_FORMED);
1565	if (scsi_wwnstr_to_wwn(addr, &wwn))
1566		return (DDI_NOT_WELL_FORMED);
1567
1568	/* Prevent duplicate nodes.  */
1569	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
1570	    smp_busctl_ua);
1571	if (dup) {
1572		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_SMP);
1573		if (ndi_flavor_get(dup) != SCSA_FLAVOR_SMP) {
1574			SCSI_HBA_LOG((_LOG(1), NULL, child,
1575			    "init failed: %s@%s: not SMP flavored",
1576			    ddi_node_name(child), addr));
1577			return (DDI_FAILURE);
1578		}
1579		if (dup != child) {
1580			SCSI_HBA_LOG((_LOG(4), NULL, child,
1581			    "init failed: %s@%s: detected duplicate %p",
1582			    ddi_node_name(child), addr, (void *)dup));
1583			return (DDI_FAILURE);
1584		}
1585	}
1586
1587
1588	/* set the node @addr string */
1589	ddi_set_name_addr(child, addr);
1590
1591	/* Allocate and initialize smp_device. */
1592	smp_sd = kmem_zalloc(sizeof (struct smp_device), KM_SLEEP);
1593	smp_sd->smp_sd_dev = child;
1594	smp_sd->smp_sd_address.smp_a_hba_tran = tran;
1595	bcopy(&wwn, smp_sd->smp_sd_address.smp_a_wwn, SAS_WWN_BYTE_SIZE);
1596
1597	ddi_set_driver_private(child, smp_sd);
1598
1599	if (tran->smp_tran_init && ((*tran->smp_tran_init)(self, child,
1600	    tran, smp_sd) != DDI_SUCCESS)) {
1601		kmem_free(smp_sd, sizeof (struct smp_device));
1602		scsi_enumeration_failed(child, -1, NULL, "smp_tran_init");
1603		ddi_set_driver_private(child, NULL);
1604		ddi_set_name_addr(child, NULL);
1605		return (DDI_FAILURE);
1606	}
1607
1608	return (DDI_SUCCESS);
1609}
1610
1611/*ARGSUSED*/
1612static int
1613smp_busctl_uninitchild(dev_info_t *child)
1614{
1615	dev_info_t		*self = ddi_get_parent(child);
1616	struct smp_device	*smp_sd = ddi_get_driver_private(child);
1617	smp_hba_tran_t		*tran;
1618
1619	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SMP);
1620	ASSERT(smp_sd && tran);
1621	if ((smp_sd == NULL) || (tran == NULL))
1622		return (DDI_FAILURE);
1623
1624	if (tran->smp_tran_free)
1625		(*tran->smp_tran_free) (self, child, tran, smp_sd);
1626
1627	kmem_free(smp_sd, sizeof (*smp_sd));
1628	ddi_set_driver_private(child, NULL);
1629	ddi_set_name_addr(child, NULL);
1630	return (DDI_SUCCESS);
1631}
1632
1633/* Find an "smp" child at the specified address. */
1634static dev_info_t *
1635smp_findchild(dev_info_t *self, char *addr)
1636{
1637	dev_info_t	*child;
1638
1639	/* Search "smp" devinfo child at specified address. */
1640	ASSERT(self && DEVI_BUSY_OWNED(self) && addr);
1641	for (child = ddi_get_child(self); child;
1642	    child = ddi_get_next_sibling(child)) {
1643		/* skip non-"smp" nodes */
1644		if (ndi_flavor_get(child) != SCSA_FLAVOR_SMP)
1645			continue;
1646
1647		/* Attempt initchild to establish unit-address */
1648		if (i_ddi_node_state(child) < DS_INITIALIZED)
1649			(void) ddi_initchild(self, child);
1650
1651		/* Verify state and non-NULL unit-address. */
1652		if ((i_ddi_node_state(child) < DS_INITIALIZED) ||
1653		    (ddi_get_name_addr(child) == NULL))
1654			continue;
1655
1656		/* Return "smp" child if unit-address matches. */
1657		if (strcmp(ddi_get_name_addr(child), addr) == 0)
1658			return (child);
1659	}
1660	return (NULL);
1661}
1662
1663/*
1664 * Search for "smp" child of self at the specified address. If found, online
1665 * and return with a hold.  Unlike general SCSI configuration, we can assume
1666 * the the device is actually there when we are called (i.e., device is
1667 * created by hotplug, not by bus_config).
1668 */
1669int
1670smp_hba_bus_config(dev_info_t *self, char *addr, dev_info_t **childp)
1671{
1672	dev_info_t	*child;
1673	int		circ;
1674
1675	ASSERT(self && addr && childp);
1676	*childp = NULL;
1677
1678	/* Search for "smp" child. */
1679	scsi_hba_devi_enter(self, &circ);
1680	if ((child = smp_findchild(self, addr)) == NULL) {
1681		scsi_hba_devi_exit(self, circ);
1682		return (NDI_FAILURE);
1683	}
1684
1685	/* Attempt online. */
1686	if (ndi_devi_online(child, 0) != NDI_SUCCESS) {
1687		scsi_hba_devi_exit(self, circ);
1688		return (NDI_FAILURE);
1689	}
1690
1691	/* On success, return with active hold. */
1692	ndi_hold_devi(child);
1693	scsi_hba_devi_exit(self, circ);
1694	*childp = child;
1695	return (NDI_SUCCESS);
1696}
1697
1698
1699
1700/* Create "smp" child devinfo node at specified unit-address. */
1701int
1702smp_hba_bus_config_taddr(dev_info_t *self, char *addr)
1703{
1704	dev_info_t		*child;
1705	int			circ;
1706
1707	/*
1708	 * NOTE: If we ever uses a generic node name (.vs. a driver name)
1709	 * or define a 'compatible' property, this code will need to use
1710	 * a 'probe' node (ala scsi_device support) to obtain identity
1711	 * information from the device.
1712	 */
1713
1714	/* Search for "smp" child. */
1715	scsi_hba_devi_enter(self, &circ);
1716	child = smp_findchild(self, addr);
1717	if (child) {
1718		/* Child exists, note if this was a new reinsert. */
1719		if (ndi_devi_device_insert(child))
1720			SCSI_HBA_LOG((_LOGCFG, self, NULL,
1721			    "devinfo smp@%s device_reinsert", addr));
1722
1723		scsi_hba_devi_exit(self, circ);
1724		return (NDI_SUCCESS);
1725	}
1726
1727	/* Allocate "smp" child devinfo node and establish flavor of child. */
1728	ndi_devi_alloc_sleep(self, "smp", DEVI_SID_HP_NODEID, &child);
1729	ASSERT(child);
1730	ndi_flavor_set(child, SCSA_FLAVOR_SMP);
1731
1732	/* Add unit-address property to child. */
1733	if (ndi_prop_update_string(DDI_DEV_T_NONE, child,
1734	    SCSI_ADDR_PROP_TARGET_PORT, addr) != DDI_PROP_SUCCESS) {
1735		(void) ndi_devi_free(child);
1736		scsi_hba_devi_exit(self, circ);
1737		return (NDI_FAILURE);
1738	}
1739
1740	/* Attempt to online the new "smp" node. */
1741	(void) ndi_devi_online(child, 0);
1742
1743	scsi_hba_devi_exit(self, circ);
1744	return (NDI_SUCCESS);
1745}
1746
1747/*
1748 * Wrapper to scsi_ua_get which takes a devinfo argument instead of a
1749 * scsi_device structure.
1750 */
1751static int
1752scsi_busctl_ua(dev_info_t *child, char *addr, int maxlen)
1753{
1754	struct scsi_device	*sd;
1755
1756	/* limit ndi_devi_findchild_by_callback to expected flavor */
1757	if (ndi_flavor_get(child) != SCSA_FLAVOR_SCSI_DEVICE)
1758		return (DDI_FAILURE);
1759
1760	/* nodes are named by tran_get_name or default "tgt,lun" */
1761	sd = ddi_get_driver_private(child);
1762	if (sd && (scsi_ua_get(sd, addr, maxlen) == 1))
1763		return (DDI_SUCCESS);
1764
1765	return (DDI_FAILURE);
1766}
1767
1768static int
1769scsi_busctl_reportdev(dev_info_t *child)
1770{
1771	dev_info_t		*self = ddi_get_parent(child);
1772	struct scsi_device	*sd = ddi_get_driver_private(child);
1773	scsi_hba_tran_t		*tran;
1774	char			ua[SCSI_MAXNAMELEN];
1775	char			ra[SCSI_MAXNAMELEN];
1776
1777	SCSI_HBA_LOG((_LOG_TRACE, NULL, child, __func__));
1778
1779	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1780	ASSERT(tran && sd);
1781	if ((tran == NULL) || (sd == NULL))
1782		return (DDI_FAILURE);
1783
1784	/* get the unit_address and bus_addr information */
1785	if ((scsi_ua_get(sd, ua, sizeof (ua)) == 0) ||
1786	    (scsi_ua_get_reportdev(sd, ra, sizeof (ra)) == 0)) {
1787		SCSI_HBA_LOG((_LOG(WARN), NULL, child, "REPORTDEV failure"));
1788		return (DDI_FAILURE);
1789	}
1790
1791	if (tran->tran_get_name == NULL)
1792		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: %s",
1793		    ddi_driver_name(child), ddi_get_instance(child),
1794		    ddi_driver_name(self), ddi_get_instance(self), ra));
1795	else if (*ra)
1796		SCSI_HBA_LOG((_LOG_NF(CONT),
1797		    "?%s%d at %s%d: unit-address %s: %s",
1798		    ddi_driver_name(child), ddi_get_instance(child),
1799		    ddi_driver_name(self), ddi_get_instance(self), ua, ra));
1800	else
1801		SCSI_HBA_LOG((_LOG_NF(CONT),
1802		    "?%s%d at %s%d: unit-address %s",
1803		    ddi_driver_name(child), ddi_get_instance(child),
1804		    ddi_driver_name(self), ddi_get_instance(self), ua));
1805
1806	return (DDI_SUCCESS);
1807}
1808
1809
1810/*
1811 * scsi_busctl_initchild is called to initialize the SCSA transport for
1812 * communication with a particular child scsi target device. Successful
1813 * initialization requires properties on the node which describe the address
1814 * of the target device. If the address of the target device can't be
1815 * determined from properties then DDI_NOT_WELL_FORMED is returned. Nodes that
1816 * are DDI_NOT_WELL_FORMED are considered an implementation artifact and
1817 * are hidden from devinfo snapshots by calling ndi_devi_set_hidden().
1818 * The child may be one of the following types of devinfo nodes:
1819 *
1820 * OBP node:
1821 *	OBP does not enumerate target devices attached a SCSI bus. These
1822 *	template/stub/wild-card nodes are a legacy artifact for support of old
1823 *	driver loading methods. Since they have no properties,
1824 *	DDI_NOT_WELL_FORMED will be returned.
1825 *
1826 * SID node:
1827 *	The node may be either a:
1828 *	    o	probe/barrier SID node
1829 *	    o	a dynamic SID target node
1830 *
1831 * driver.conf node: The situation for this nexus is different than most.
1832 *	Typically a driver.conf node definition is used to either define a
1833 *	new child devinfo node or to further decorate (via merge) a SID
1834 *	child with properties. In our case we use the nodes for *both*
1835 *	purposes.
1836 *
1837 * In both the SID node and driver.conf node cases we must form the nodes
1838 * "@addr" from the well-known scsi(9P) device unit-address properties on
1839 * the node.
1840 *
1841 * For HBA drivers that implement the deprecated tran_get_name interface,
1842 * "@addr" construction involves having that driver interpret properties via
1843 * scsi_busctl_ua -> scsi_ua_get -> tran_get_name: there is no
1844 * requirement for the property names to be well-known.
1845 *
1846 * NOTE: We don't currently support "merge".  When this support is added a
1847 * specific property, like "unit-address", should *always* identify a
1848 * driver.conf node that needs to be merged into a specific SID node. When
1849 * enumeration is enabled, a .conf node without the "unit-address" property
1850 * should be ignored.  The best way to establish the "unit-address" property
1851 * would be to have the system assign parent= and unit-address= from an
1852 * instance=# driver.conf entry (by using the instance tree).
1853 */
1854static int
1855scsi_busctl_initchild(dev_info_t *child)
1856{
1857	dev_info_t		*self = ddi_get_parent(child);
1858	dev_info_t		*dup;
1859	scsi_hba_tran_t		*tran;
1860	struct scsi_device	*sd;
1861	scsi_hba_tran_t		*tran_clone;
1862	char			*class;
1863	int			tgt;
1864	int			lun;
1865	int			sfunc;
1866	int			err = DDI_FAILURE;
1867	char			addr[SCSI_MAXNAMELEN];
1868
1869	ASSERT(DEVI_BUSY_OWNED(self));
1870	SCSI_HBA_LOG((_LOG(4), NULL, child, "init begin"));
1871
1872	/*
1873	 * For a driver like fp with multiple upper-layer-protocols
1874	 * it is possible for scsi_hba_init in _init to plumb SCSA
1875	 * and have the load of fcp (which does scsi_hba_attach_setup)
1876	 * to fail.  In this case we may get here with a NULL hba.
1877	 */
1878	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
1879	if (tran == NULL)
1880		return (DDI_NOT_WELL_FORMED);
1881
1882	/*
1883	 * OBP may create template/stub/wild-card nodes for legacy driver
1884	 * loading methods. These nodes have no properties, so we lack the
1885	 * addressing properties to initchild them. Hide the node and return
1886	 * DDI_NOT_WELL_FORMED.
1887	 *
1888	 * Future: define/use a ndi_devi_has_properties(dip) type interface.
1889	 *
1890	 * NOTE: It would be nice if we could delete these ill formed nodes by
1891	 * implementing a DDI_NOT_WELL_FORMED_DELETE return code. This can't
1892	 * be done until leadville debug code removes its dependencies
1893	 * on the devinfo still being present after a failed ndi_devi_online.
1894	 */
1895	if ((DEVI(child)->devi_hw_prop_ptr == NULL) &&
1896	    (DEVI(child)->devi_drv_prop_ptr == NULL) &&
1897	    (DEVI(child)->devi_sys_prop_ptr == NULL)) {
1898		SCSI_HBA_LOG((_LOG(4), NULL, child,
1899		    "init failed: no properties"));
1900		ndi_devi_set_hidden(child);
1901		return (DDI_NOT_WELL_FORMED);
1902	}
1903
1904	/* get legacy SPI addressing properties */
1905	if ((tgt = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1906	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
1907	    SCSI_ADDR_PROP_TARGET, -1)) == -1) {
1908		tgt = 0;
1909		/*
1910		 * A driver.conf node for merging always has a target= property,
1911		 * even if it is just a dummy that does not contain the real
1912		 * target address. However drivers that register devids may
1913		 * create stub driver.conf nodes without a target= property so
1914		 * that pathological devid resolution works. Hide the stub
1915		 * node and return DDI_NOT_WELL_FORMED.
1916		 */
1917		if (!scsi_hba_dev_is_sid(child)) {
1918			SCSI_HBA_LOG((_LOG(4), NULL, child,
1919			    "init failed: stub .conf node"));
1920			ndi_devi_set_hidden(child);
1921			return (DDI_NOT_WELL_FORMED);
1922		}
1923	}
1924	lun = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1925	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, SCSI_ADDR_PROP_LUN, 0);
1926	sfunc = ddi_prop_get_int(DDI_DEV_T_ANY, child,
1927	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, SCSI_ADDR_PROP_SFUNC, -1);
1928
1929	/*
1930	 * The scsi_address structure may not specify all the addressing
1931	 * information. For an old HBA that doesn't support tran_get_name
1932	 * (most pre-SCSI-3 HBAs) the scsi_address structure is still used,
1933	 * so the target property must exist and the LUN must be < 256.
1934	 */
1935	if ((tran->tran_get_name == NULL) &&
1936	    ((tgt >= USHRT_MAX) || (lun >= 256))) {
1937		SCSI_HBA_LOG((_LOG(1), NULL, child,
1938		    "init failed: illegal/missing properties"));
1939		ndi_devi_set_hidden(child);
1940		return (DDI_NOT_WELL_FORMED);
1941	}
1942
1943	/*
1944	 * We need to initialize a fair amount of our environment to invoke
1945	 * tran_get_name (via scsi_busctl_ua and scsi_ua_get) to
1946	 * produce the "@addr" name from addressing properties. Allocate and
1947	 * initialize scsi device structure.
1948	 */
1949	sd = kmem_zalloc(sizeof (struct scsi_device), KM_SLEEP);
1950	mutex_init(&sd->sd_mutex, NULL, MUTEX_DRIVER, NULL);
1951	sd->sd_dev = child;
1952	sd->sd_pathinfo = NULL;
1953	sd->sd_uninit_prevent = 0;
1954	ddi_set_driver_private(child, sd);
1955
1956	if (tran->tran_hba_flags & SCSI_HBA_ADDR_COMPLEX) {
1957		/*
1958		 * For a SCSI_HBA_ADDR_COMPLEX transport we store a pointer to
1959		 * scsi_device in the scsi_address structure.  This allows an
1960		 * HBA driver to find its per-scsi_device private data
1961		 * (accessible to the HBA given just the scsi_address by using
1962		 *  scsi_address_device(9F)/scsi_device_hba_private_get(9F)).
1963		 */
1964		sd->sd_address.a.a_sd = sd;
1965		tran_clone = NULL;
1966	} else {
1967		/*
1968		 * Initialize the scsi_address so that a SCSI-2 target driver
1969		 * talking to a SCSI-2 device on a SCSI-3 bus (spi) continues
1970		 * to work. We skew the secondary function value so that we
1971		 * can tell from the address structure if we are processing
1972		 * a secondary function request.
1973		 */
1974		sd->sd_address.a_target = (ushort_t)tgt;
1975		sd->sd_address.a_lun = (uchar_t)lun;
1976		if (sfunc == -1)
1977			sd->sd_address.a_sublun = (uchar_t)0;
1978		else
1979			sd->sd_address.a_sublun = (uchar_t)sfunc + 1;
1980
1981		/*
1982		 * NOTE: Don't limit LUNs to scsi_options value because a
1983		 * scsi_device discovered via SPI dynamic enumeration might
1984		 * still support SCMD_REPORT_LUNS.
1985		 */
1986
1987		/*
1988		 * Deprecated: Use SCSI_HBA_ADDR_COMPLEX:
1989		 *   Clone transport structure if requested. Cloning allows
1990		 *   an HBA to maintain target-specific information if
1991		 *   necessary, such as target addressing information that
1992		 *   does not adhere to the scsi_address structure format.
1993		 */
1994		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
1995			tran_clone = kmem_alloc(
1996			    sizeof (scsi_hba_tran_t), KM_SLEEP);
1997			bcopy((caddr_t)tran,
1998			    (caddr_t)tran_clone, sizeof (scsi_hba_tran_t));
1999			tran = tran_clone;
2000			tran->tran_sd = sd;
2001		} else {
2002			tran_clone = NULL;
2003			ASSERT(tran->tran_sd == NULL);
2004		}
2005	}
2006
2007	/* establish scsi_address pointer to the HBA's tran structure */
2008	sd->sd_address.a_hba_tran = tran;
2009
2010	/*
2011	 * This is a grotty hack that allows direct-access (non-scsa) drivers
2012	 * (like chs, ata, and mlx which all make cmdk children) to put its
2013	 * own vector in the 'a_hba_tran' field. When all the drivers that do
2014	 * this are fixed, please remove this hack.
2015	 *
2016	 * NOTE: This hack is also shows up in the DEVP_TO_TRAN implementation
2017	 * in scsi_confsubr.c.
2018	 */
2019	sd->sd_tran_safe = tran;
2020
2021	/*
2022	 * If the class property is not already established, set it to "scsi".
2023	 * This is done so that parent= driver.conf nodes have class.
2024	 */
2025	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2026	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "class",
2027	    &class) == DDI_PROP_SUCCESS) {
2028		ddi_prop_free(class);
2029	} else if (ndi_prop_update_string(DDI_DEV_T_NONE, child,
2030	    "class", "scsi") != DDI_PROP_SUCCESS) {
2031		SCSI_HBA_LOG((_LOG(2), NULL, child, "init failed: class"));
2032		ndi_devi_set_hidden(child);
2033		err = DDI_NOT_WELL_FORMED;
2034		goto failure;
2035	}
2036
2037	/* Establish the @addr name of the child. */
2038	*addr = '\0';
2039	if (scsi_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS) {
2040		/*
2041		 * Some driver.conf files add bogus target properties (relative
2042		 * to their nexus representation of target) to their stub
2043		 * nodes, causing the check above to not filter them.
2044		 */
2045		SCSI_HBA_LOG((_LOG(3), NULL, child,
2046		    "init failed: scsi_busctl_ua call"));
2047		ndi_devi_set_hidden(child);
2048		err = DDI_NOT_WELL_FORMED;
2049		goto failure;
2050	}
2051	if (*addr == '\0') {
2052		SCSI_HBA_LOG((_LOG(2), NULL, child, "init failed: ua"));
2053		ndi_devi_set_hidden(child);
2054		err = DDI_NOT_WELL_FORMED;
2055		goto failure;
2056	}
2057
2058	/* Prevent duplicate nodes.  */
2059	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
2060	    scsi_busctl_ua);
2061	if (dup) {
2062		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_SCSI_DEVICE);
2063		if (ndi_flavor_get(dup) != SCSA_FLAVOR_SCSI_DEVICE) {
2064			SCSI_HBA_LOG((_LOG(1), NULL, child,
2065			    "init failed: %s@%s: not SCSI_DEVICE flavored",
2066			    ddi_node_name(child), addr));
2067			goto failure;
2068		}
2069		if (dup != child) {
2070			SCSI_HBA_LOG((_LOG(4), NULL, child,
2071			    "init failed: %s@%s: detected duplicate %p",
2072			    ddi_node_name(child), addr, (void *)dup));
2073			goto failure;
2074		}
2075	}
2076
2077	/* set the node @addr string */
2078	ddi_set_name_addr(child, addr);
2079
2080	/* call HBA's target init entry point if it exists */
2081	if (tran->tran_tgt_init != NULL) {
2082		SCSI_HBA_LOG((_LOG(4), NULL, child, "init tran_tgt_init"));
2083		sd->sd_tran_tgt_free_done = 0;
2084		if ((*tran->tran_tgt_init)
2085		    (self, child, tran, sd) != DDI_SUCCESS) {
2086			scsi_enumeration_failed(child, -1, NULL,
2087			    "tran_tgt_init");
2088			goto failure;
2089		}
2090	}
2091
2092	SCSI_HBA_LOG((_LOG(3), NULL, child, "init successful"));
2093	return (DDI_SUCCESS);
2094
2095failure:
2096	if (tran_clone)
2097		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
2098	mutex_destroy(&sd->sd_mutex);
2099	kmem_free(sd, sizeof (*sd));
2100	ddi_set_driver_private(child, NULL);
2101	ddi_set_name_addr(child, NULL);
2102
2103	return (err);		/* remove the node */
2104}
2105
2106static int
2107scsi_busctl_uninitchild(dev_info_t *child)
2108{
2109	dev_info_t		*self = ddi_get_parent(child);
2110	struct scsi_device	*sd = ddi_get_driver_private(child);
2111	scsi_hba_tran_t		*tran;
2112	scsi_hba_tran_t		*tran_clone;
2113
2114	ASSERT(DEVI_BUSY_OWNED(self));
2115
2116	tran = ndi_flavorv_get(self, SCSA_FLAVOR_SCSI_DEVICE);
2117	ASSERT(tran && sd);
2118	if ((tran == NULL) || (sd == NULL))
2119		return (DDI_FAILURE);
2120
2121	/*
2122	 * We use sd_uninit_prevent to avoid uninitializing barrier/probe
2123	 * nodes that are still in use. Since barrier/probe nodes are not
2124	 * attached we can't prevent their state demotion via ndi_hold_devi.
2125	 */
2126	if (sd->sd_uninit_prevent) {
2127		SCSI_HBA_LOG((_LOG(2), NULL, child, "uninit prevented"));
2128		return (DDI_FAILURE);
2129	}
2130
2131	/*
2132	 * Don't uninitialize a client node if it still has paths.
2133	 */
2134	if (MDI_CLIENT(child) && mdi_client_get_path_count(child)) {
2135		SCSI_HBA_LOG((_LOG(2), NULL, child,
2136		    "uninit prevented, client has paths"));
2137		return (DDI_FAILURE);
2138	}
2139
2140	SCSI_HBA_LOG((_LOG(3), NULL, child, "uninit begin"));
2141
2142	if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE) {
2143		tran_clone = sd->sd_address.a_hba_tran;
2144
2145		/* ... grotty hack, involving sd_tran_safe, continued. */
2146		if (tran_clone != sd->sd_tran_safe) {
2147			tran_clone = sd->sd_tran_safe;
2148#ifdef	DEBUG
2149			/*
2150			 * Complain so things get fixed and hack can, at
2151			 * some point in time, be removed.
2152			 */
2153			SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2154			    "'%s' is corrupting a_hba_tran", sd->sd_dev ?
2155			    ddi_driver_name(sd->sd_dev) : "unknown_driver"));
2156#endif	/* DEBUG */
2157		}
2158
2159		ASSERT(tran_clone->tran_hba_flags & SCSI_HBA_TRAN_CLONE);
2160		ASSERT(tran_clone->tran_sd == sd);
2161		tran = tran_clone;
2162	} else {
2163		tran_clone = NULL;
2164		ASSERT(tran->tran_sd == NULL);
2165	}
2166
2167	/*
2168	 * To simplify host adapter drivers we guarantee that multiple
2169	 * tran_tgt_init(9E) calls of the same unit address are never
2170	 * active at the same time.  This requires that we always call
2171	 * tran_tgt_free on probe/barrier nodes directly prior to
2172	 * uninitchild.
2173	 *
2174	 * NOTE: To correctly support SCSI_HBA_TRAN_CLONE, we must use
2175	 * the (possibly cloned) hba_tran pointer from the scsi_device
2176	 * instead of hba_tran.
2177	 */
2178	if (tran->tran_tgt_free) {
2179		if (!sd->sd_tran_tgt_free_done) {
2180			SCSI_HBA_LOG((_LOG(4), NULL, child,
2181			    "uninit tran_tgt_free"));
2182			(*tran->tran_tgt_free) (self, child, tran, sd);
2183			sd->sd_tran_tgt_free_done = 1;
2184		} else {
2185			SCSI_HBA_LOG((_LOG(4), NULL, child,
2186			    "uninit tran_tgt_free already done"));
2187		}
2188	}
2189
2190	/*
2191	 * If a inquiry data is still allocated (by scsi_probe()) we
2192	 * free the allocation here. This keeps scsi_inq valid for the
2193	 * same duration as the corresponding inquiry properties. It
2194	 * also allows a tran_tgt_init() implementation that establishes
2195	 * sd_inq to deal with deallocation in its tran_tgt_free
2196	 * (setting sd_inq back to NULL) without upsetting the
2197	 * framework. Moving the inquiry free here also allows setting
2198	 * of sd_uninit_prevent to preserve the data for lun0 based
2199	 * scsi_get_device_type_scsi_options() calls.
2200	 */
2201	if (sd->sd_inq) {
2202		kmem_free(sd->sd_inq, SUN_INQSIZE);
2203		sd->sd_inq = (struct scsi_inquiry *)NULL;
2204	}
2205
2206	mutex_destroy(&sd->sd_mutex);
2207	if (tran_clone)
2208		kmem_free(tran_clone, sizeof (scsi_hba_tran_t));
2209	kmem_free(sd, sizeof (*sd));
2210
2211	ddi_set_driver_private(child, NULL);
2212	SCSI_HBA_LOG((_LOG(3), NULL, child, "uninit complete"));
2213	ddi_set_name_addr(child, NULL);
2214	return (DDI_SUCCESS);
2215}
2216
2217static int
2218iport_busctl_ua(dev_info_t *child, char *addr, int maxlen)
2219{
2220	char	*iport_ua;
2221
2222	/* limit ndi_devi_findchild_by_callback to expected flavor */
2223	if (ndi_flavor_get(child) != SCSA_FLAVOR_IPORT)
2224		return (DDI_FAILURE);
2225
2226	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2227	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2228	    SCSI_ADDR_PROP_IPORTUA, &iport_ua) != DDI_SUCCESS) {
2229		return (DDI_FAILURE);
2230	}
2231
2232	(void) snprintf(addr, maxlen, "%s", iport_ua);
2233	ddi_prop_free(iport_ua);
2234	return (DDI_SUCCESS);
2235}
2236
2237static int
2238iport_busctl_reportdev(dev_info_t *child)
2239{
2240	dev_info_t	*self = ddi_get_parent(child);
2241	char		*iport_ua;
2242	char		*initiator_port = NULL;
2243
2244	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2245	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2246	    SCSI_ADDR_PROP_IPORTUA, &iport_ua) != DDI_SUCCESS)
2247		return (DDI_FAILURE);
2248
2249	(void) ddi_prop_lookup_string(DDI_DEV_T_ANY, child,
2250	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
2251	    SCSI_ADDR_PROP_INITIATOR_PORT, &initiator_port);
2252
2253	if (initiator_port) {
2254		SCSI_HBA_LOG((_LOG_NF(CONT),
2255		    "?%s%d at %s%d: %s %s %s %s",
2256		    ddi_driver_name(child), ddi_get_instance(child),
2257		    ddi_driver_name(self), ddi_get_instance(self),
2258		    SCSI_ADDR_PROP_INITIATOR_PORT, initiator_port,
2259		    SCSI_ADDR_PROP_IPORTUA, iport_ua));
2260		ddi_prop_free(initiator_port);
2261	} else {
2262		SCSI_HBA_LOG((_LOG_NF(CONT), "?%s%d at %s%d: %s %s",
2263		    ddi_driver_name(child), ddi_get_instance(child),
2264		    ddi_driver_name(self), ddi_get_instance(self),
2265		    SCSI_ADDR_PROP_IPORTUA, iport_ua));
2266	}
2267	ddi_prop_free(iport_ua);
2268	return (DDI_SUCCESS);
2269}
2270
2271/* initchild SCSA iport 'child' node */
2272static int
2273iport_busctl_initchild(dev_info_t *child)
2274{
2275	dev_info_t	*self = ddi_get_parent(child);
2276	dev_info_t	*dup = NULL;
2277	char		addr[SCSI_MAXNAMELEN];
2278
2279	if (iport_busctl_ua(child, addr, sizeof (addr)) != DDI_SUCCESS)
2280		return (DDI_NOT_WELL_FORMED);
2281
2282	/* Prevent duplicate nodes.  */
2283	dup = ndi_devi_findchild_by_callback(self, ddi_node_name(child), addr,
2284	    iport_busctl_ua);
2285	if (dup) {
2286		ASSERT(ndi_flavor_get(dup) == SCSA_FLAVOR_IPORT);
2287		if (ndi_flavor_get(dup) != SCSA_FLAVOR_IPORT) {
2288			SCSI_HBA_LOG((_LOG(1), NULL, child,
2289			    "init failed: %s@%s: not IPORT flavored",
2290			    ddi_node_name(child), addr));
2291			return (DDI_FAILURE);
2292		}
2293		if (dup != child) {
2294			SCSI_HBA_LOG((_LOG(4), NULL, child,
2295			    "init failed: %s@%s: detected duplicate %p",
2296			    ddi_node_name(child), addr, (void *)dup));
2297			return (DDI_FAILURE);
2298		}
2299	}
2300
2301	/* set the node @addr string */
2302	ddi_set_name_addr(child, addr);
2303
2304	return (DDI_SUCCESS);
2305}
2306
2307/* uninitchild SCSA iport 'child' node */
2308static int
2309iport_busctl_uninitchild(dev_info_t *child)
2310{
2311	ddi_set_name_addr(child, NULL);
2312	return (DDI_SUCCESS);
2313}
2314
2315/* Uninitialize scsi_device flavor of transport on SCSA iport 'child' node. */
2316static void
2317iport_postdetach_tran_scsi_device(dev_info_t *child)
2318{
2319	scsi_hba_tran_t		*tran;
2320
2321	tran = ndi_flavorv_get(child, SCSA_FLAVOR_SCSI_DEVICE);
2322	if (tran == NULL)
2323		return;
2324
2325	scsa_tran_teardown(child, tran);
2326	scsa_nexus_teardown(child, tran);
2327
2328	ndi_flavorv_set(child, SCSA_FLAVOR_SCSI_DEVICE, NULL);
2329	scsi_hba_tran_free(tran);
2330}
2331
2332/* Initialize scsi_device flavor of transport on SCSA iport 'child' node. */
2333static void
2334iport_preattach_tran_scsi_device(dev_info_t *child)
2335{
2336	dev_info_t	*hba = ddi_get_parent(child);
2337	scsi_hba_tran_t	*htran;
2338	scsi_hba_tran_t	*tran;
2339
2340	/* parent HBA node scsi_device tran is required */
2341	htran = ndi_flavorv_get(hba, SCSA_FLAVOR_SCSI_DEVICE);
2342	ASSERT(htran);
2343
2344	/* Allocate iport child's scsi_device transport vector */
2345	tran = scsi_hba_tran_alloc(child, SCSI_HBA_CANSLEEP);
2346	ASSERT(tran);
2347
2348	/* Structure-copy scsi_device transport of HBA to iport. */
2349	*tran = *htran;
2350
2351	/*
2352	 * Reset scsi_device transport fields not shared with the
2353	 * parent, and not established below.
2354	 */
2355	tran->tran_open_flag = 0;
2356	tran->tran_hba_private = NULL;
2357
2358	/* Establish the devinfo context of this tran structure. */
2359	tran->tran_iport_dip = child;
2360
2361	/* Clear SCSI_HBA_SCSA flags (except TA) */
2362	tran->tran_hba_flags &=
2363	    ~(SCSI_HBA_SCSA_FM | SCSI_HBA_SCSA_PHCI);	/* clear parent state */
2364	tran->tran_hba_flags |= SCSI_HBA_SCSA_TA;	/* always TA */
2365	tran->tran_hba_flags &= ~SCSI_HBA_HBA;		/* never HBA */
2366
2367	/* Establish flavor of transport (and ddi_get_driver_private()) */
2368	ndi_flavorv_set(child, SCSA_FLAVOR_SCSI_DEVICE, tran);
2369
2370	/* Setup iport node */
2371	if ((scsa_nexus_setup(child, tran) != DDI_SUCCESS) ||
2372	    (scsa_tran_setup(child, tran) != DDI_SUCCESS))
2373		iport_postdetach_tran_scsi_device(child);
2374}
2375
2376/* Uninitialize smp_device flavor of transport on SCSA iport 'child' node. */
2377static void
2378iport_postdetach_tran_smp_device(dev_info_t *child)
2379{
2380	smp_hba_tran_t	*tran;
2381
2382	tran = ndi_flavorv_get(child, SCSA_FLAVOR_SMP);
2383	if (tran == NULL)
2384		return;
2385
2386	ndi_flavorv_set(child, SCSA_FLAVOR_SMP, NULL);
2387	smp_hba_tran_free(tran);
2388}
2389
2390/* Initialize smp_device flavor of transport on SCSA iport 'child' node. */
2391static void
2392iport_preattach_tran_smp_device(dev_info_t *child)
2393{
2394	dev_info_t	*hba = ddi_get_parent(child);
2395	smp_hba_tran_t	*htran;
2396	smp_hba_tran_t	*tran;
2397
2398	/* parent HBA node smp_device tran is optional */
2399	htran = ndi_flavorv_get(hba, SCSA_FLAVOR_SMP);
2400	if (htran == NULL) {
2401		ndi_flavorv_set(child, SCSA_FLAVOR_SMP, NULL);
2402		return;
2403	}
2404
2405	/* Allocate iport child's smp_device transport vector */
2406	tran = smp_hba_tran_alloc(child);
2407
2408	/* Structure-copy smp_device transport of HBA to iport. */
2409	*tran = *htran;
2410
2411	/* Establish flavor of transport */
2412	ndi_flavorv_set(child, SCSA_FLAVOR_SMP, tran);
2413}
2414
2415/*
2416 * Generic bus_ctl operations for SCSI HBA's,
2417 * hiding the busctl interface from the HBA.
2418 */
2419/*ARGSUSED*/
2420static int
2421scsi_hba_bus_ctl(
2422	dev_info_t		*self,
2423	dev_info_t		*child,
2424	ddi_ctl_enum_t		op,
2425	void			*arg,
2426	void			*result)
2427{
2428	int			child_flavor = 0;
2429	int			val;
2430	ddi_dma_attr_t		*attr;
2431	scsi_hba_tran_t		*tran;
2432	struct attachspec	*as;
2433	struct detachspec	*ds;
2434
2435	/* For some ops, child is 'arg'. */
2436	if ((op == DDI_CTLOPS_INITCHILD) || (op == DDI_CTLOPS_UNINITCHILD))
2437		child = (dev_info_t *)arg;
2438
2439	/* Determine the flavor of the child: scsi, smp, iport */
2440	child_flavor = ndi_flavor_get(child);
2441
2442	switch (op) {
2443	case DDI_CTLOPS_INITCHILD:
2444		switch (child_flavor) {
2445		case SCSA_FLAVOR_SCSI_DEVICE:
2446			return (scsi_busctl_initchild(child));
2447		case SCSA_FLAVOR_SMP:
2448			return (smp_busctl_initchild(child));
2449		case SCSA_FLAVOR_IPORT:
2450			return (iport_busctl_initchild(child));
2451		default:
2452			return (DDI_FAILURE);
2453		}
2454		/* NOTREACHED */
2455
2456	case DDI_CTLOPS_UNINITCHILD:
2457		switch (child_flavor) {
2458		case SCSA_FLAVOR_SCSI_DEVICE:
2459			return (scsi_busctl_uninitchild(child));
2460		case SCSA_FLAVOR_SMP:
2461			return (smp_busctl_uninitchild(child));
2462		case SCSA_FLAVOR_IPORT:
2463			return (iport_busctl_uninitchild(child));
2464		default:
2465			return (DDI_FAILURE);
2466		}
2467		/* NOTREACHED */
2468
2469	case DDI_CTLOPS_REPORTDEV:
2470		switch (child_flavor) {
2471		case SCSA_FLAVOR_SCSI_DEVICE:
2472			return (scsi_busctl_reportdev(child));
2473		case SCSA_FLAVOR_SMP:
2474			return (smp_busctl_reportdev(child));
2475		case SCSA_FLAVOR_IPORT:
2476			return (iport_busctl_reportdev(child));
2477		default:
2478			return (DDI_FAILURE);
2479		}
2480		/* NOTREACHED */
2481
2482	case DDI_CTLOPS_ATTACH:
2483		as = (struct attachspec *)arg;
2484
2485		if (child_flavor != SCSA_FLAVOR_IPORT)
2486			return (DDI_SUCCESS);
2487
2488		/* iport processing */
2489		if (as->when == DDI_PRE) {
2490			/* setup pre attach(9E) */
2491			iport_preattach_tran_scsi_device(child);
2492			iport_preattach_tran_smp_device(child);
2493		} else if ((as->when == DDI_POST) &&
2494		    (as->result != DDI_SUCCESS)) {
2495			/* cleanup if attach(9E) failed */
2496			iport_postdetach_tran_scsi_device(child);
2497			iport_postdetach_tran_smp_device(child);
2498		}
2499		return (DDI_SUCCESS);
2500
2501	case DDI_CTLOPS_DETACH:
2502		ds = (struct detachspec *)arg;
2503
2504		if (child_flavor != SCSA_FLAVOR_IPORT)
2505			return (DDI_SUCCESS);
2506
2507		/* iport processing */
2508		if ((ds->when == DDI_POST) &&
2509		    (ds->result == DDI_SUCCESS)) {
2510			/* cleanup if detach(9E) was successful */
2511			iport_postdetach_tran_scsi_device(child);
2512			iport_postdetach_tran_smp_device(child);
2513		}
2514		return (DDI_SUCCESS);
2515
2516	case DDI_CTLOPS_IOMIN:
2517		tran = ddi_get_driver_private(self);
2518		ASSERT(tran);
2519		if (tran == NULL)
2520			return (DDI_FAILURE);
2521
2522		/*
2523		 * The 'arg' value of nonzero indicates 'streaming'
2524		 * mode. If in streaming mode, pick the largest
2525		 * of our burstsizes available and say that that
2526		 * is our minimum value (modulo what minxfer is).
2527		 */
2528		attr = &tran->tran_dma_attr;
2529		val = *((int *)result);
2530		val = maxbit(val, attr->dma_attr_minxfer);
2531		*((int *)result) = maxbit(val, ((intptr_t)arg ?
2532		    (1<<ddi_ffs(attr->dma_attr_burstsizes)-1) :
2533		    (1<<(ddi_fls(attr->dma_attr_burstsizes)-1))));
2534
2535		return (ddi_ctlops(self, child, op, arg, result));
2536
2537	case DDI_CTLOPS_SIDDEV:
2538		return (ndi_dev_is_persistent_node(child) ?
2539		    DDI_SUCCESS : DDI_FAILURE);
2540
2541	case DDI_CTLOPS_POWER:
2542		return (DDI_SUCCESS);
2543
2544	/*
2545	 * These ops correspond to functions that "shouldn't" be called
2546	 * by a SCSI target driver. So we whine when we're called.
2547	 */
2548	case DDI_CTLOPS_DMAPMAPC:
2549	case DDI_CTLOPS_REPORTINT:
2550	case DDI_CTLOPS_REGSIZE:
2551	case DDI_CTLOPS_NREGS:
2552	case DDI_CTLOPS_SLAVEONLY:
2553	case DDI_CTLOPS_AFFINITY:
2554	case DDI_CTLOPS_POKE:
2555	case DDI_CTLOPS_PEEK:
2556		SCSI_HBA_LOG((_LOG(WARN), self, NULL, "invalid op (%d)", op));
2557		return (DDI_FAILURE);
2558
2559	/* Everything else we pass up */
2560	case DDI_CTLOPS_PTOB:
2561	case DDI_CTLOPS_BTOP:
2562	case DDI_CTLOPS_BTOPR:
2563	case DDI_CTLOPS_DVMAPAGESIZE:
2564	default:
2565		return (ddi_ctlops(self, child, op, arg, result));
2566	}
2567	/* NOTREACHED */
2568}
2569
2570/*
2571 * Private wrapper for scsi_pkt's allocated via scsi_hba_pkt_alloc()
2572 */
2573struct scsi_pkt_wrapper {
2574	struct scsi_pkt		scsi_pkt;
2575	int			pkt_wrapper_magic;
2576	int			pkt_wrapper_len;
2577};
2578
2579#if !defined(lint)
2580_NOTE(SCHEME_PROTECTS_DATA("unique per thread", scsi_pkt_wrapper))
2581_NOTE(SCHEME_PROTECTS_DATA("Unshared Data", dev_ops))
2582#endif
2583
2584/*
2585 * Called by an HBA to allocate a scsi_pkt
2586 */
2587/*ARGSUSED*/
2588struct scsi_pkt *
2589scsi_hba_pkt_alloc(
2590	dev_info_t		*self,
2591	struct scsi_address	*ap,
2592	int			cmdlen,
2593	int			statuslen,
2594	int			tgtlen,
2595	int			hbalen,
2596	int			(*callback)(caddr_t arg),
2597	caddr_t			arg)
2598{
2599	struct scsi_pkt		*pkt;
2600	struct scsi_pkt_wrapper	*hba_pkt;
2601	caddr_t			p;
2602	int			acmdlen, astatuslen, atgtlen, ahbalen;
2603	int			pktlen;
2604
2605	/* Sanity check */
2606	if (callback != SLEEP_FUNC && callback != NULL_FUNC)
2607		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2608		    "callback must be SLEEP_FUNC or NULL_FUNC"));
2609
2610	/*
2611	 * Round up so everything gets allocated on long-word boundaries
2612	 */
2613	acmdlen = ROUNDUP(cmdlen);
2614	astatuslen = ROUNDUP(statuslen);
2615	atgtlen = ROUNDUP(tgtlen);
2616	ahbalen = ROUNDUP(hbalen);
2617	pktlen = sizeof (struct scsi_pkt_wrapper) +
2618	    acmdlen + astatuslen + atgtlen + ahbalen;
2619
2620	hba_pkt = kmem_zalloc(pktlen,
2621	    (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP);
2622	if (hba_pkt == NULL) {
2623		ASSERT(callback == NULL_FUNC);
2624		return (NULL);
2625	}
2626
2627	/*
2628	 * Set up our private info on this pkt
2629	 */
2630	hba_pkt->pkt_wrapper_len = pktlen;
2631	hba_pkt->pkt_wrapper_magic = PKT_WRAPPER_MAGIC;	/* alloced correctly */
2632	pkt = &hba_pkt->scsi_pkt;
2633
2634	/*
2635	 * Set up pointers to private data areas, cdb, and status.
2636	 */
2637	p = (caddr_t)(hba_pkt + 1);
2638	if (hbalen > 0) {
2639		pkt->pkt_ha_private = (opaque_t)p;
2640		p += ahbalen;
2641	}
2642	if (tgtlen > 0) {
2643		pkt->pkt_private = (opaque_t)p;
2644		p += atgtlen;
2645	}
2646	if (statuslen > 0) {
2647		pkt->pkt_scbp = (uchar_t *)p;
2648		p += astatuslen;
2649	}
2650	if (cmdlen > 0) {
2651		pkt->pkt_cdbp = (uchar_t *)p;
2652	}
2653
2654	/*
2655	 * Initialize the pkt's scsi_address
2656	 */
2657	pkt->pkt_address = *ap;
2658
2659	/*
2660	 * NB: It may not be safe for drivers, esp target drivers, to depend
2661	 * on the following fields being set until all the scsi_pkt
2662	 * allocation violations discussed in scsi_pkt.h are all resolved.
2663	 */
2664	pkt->pkt_cdblen = cmdlen;
2665	pkt->pkt_tgtlen = tgtlen;
2666	pkt->pkt_scblen = statuslen;
2667
2668	return (pkt);
2669}
2670
2671/*
2672 * Called by an HBA to free a scsi_pkt
2673 */
2674/*ARGSUSED*/
2675void
2676scsi_hba_pkt_free(
2677	struct scsi_address	*ap,
2678	struct scsi_pkt		*pkt)
2679{
2680	kmem_free(pkt, ((struct scsi_pkt_wrapper *)pkt)->pkt_wrapper_len);
2681}
2682
2683/*
2684 * Return 1 if the scsi_pkt used a proper allocator.
2685 *
2686 * The DDI does not allow a driver to allocate it's own scsi_pkt(9S), a
2687 * driver should not have *any* compiled in dependencies on "sizeof (struct
2688 * scsi_pkt)". While this has been the case for many years, a number of
2689 * drivers have still not been fixed. This function can be used to detect
2690 * improperly allocated scsi_pkt structures, and produce messages identifying
2691 * drivers that need to be fixed.
2692 *
2693 * While drivers in violation are being fixed, this function can also
2694 * be used by the framework to detect packets that violated allocation
2695 * rules.
2696 *
2697 * NB: It is possible, but very unlikely, for this code to return a false
2698 * positive (finding correct magic, but for wrong reasons).  Careful
2699 * consideration is needed for callers using this interface to condition
2700 * access to newer scsi_pkt fields (those after pkt_reason).
2701 *
2702 * NB: As an aid to minimizing the amount of work involved in 'fixing' legacy
2703 * drivers that violate scsi_*(9S) allocation rules, private
2704 * scsi_pkt_size()/scsi_size_clean() functions are available (see their
2705 * implementation for details).
2706 *
2707 * *** Non-legacy use of scsi_pkt_size() is discouraged. ***
2708 *
2709 * NB: When supporting broken HBA drivers is not longer a concern, this
2710 * code should be removed.
2711 */
2712int
2713scsi_pkt_allocated_correctly(struct scsi_pkt *pkt)
2714{
2715	struct scsi_pkt_wrapper	*hba_pkt = (struct scsi_pkt_wrapper *)pkt;
2716	int	magic;
2717	major_t	major;
2718#ifdef	DEBUG
2719	int	*pspwm, *pspcwm;
2720
2721	/*
2722	 * We are getting scsi packets from two 'correct' wrapper schemes,
2723	 * make sure we are looking at the same place in both to detect
2724	 * proper allocation.
2725	 */
2726	pspwm = &((struct scsi_pkt_wrapper *)0)->pkt_wrapper_magic;
2727	pspcwm = &((struct scsi_pkt_cache_wrapper *)0)->pcw_magic;
2728	ASSERT(pspwm == pspcwm);
2729#endif	/* DEBUG */
2730
2731
2732	/*
2733	 * Check to see if driver is scsi_size_clean(), assume it
2734	 * is using the scsi_pkt_size() interface everywhere it needs to
2735	 * if the driver indicates it is scsi_size_clean().
2736	 */
2737	major = ddi_driver_major(P_TO_TRAN(pkt)->tran_hba_dip);
2738	if (devnamesp[major].dn_flags & DN_SCSI_SIZE_CLEAN)
2739		return (1);		/* ok */
2740
2741	/*
2742	 * Special case crossing a page boundary. If the scsi_pkt was not
2743	 * allocated correctly, then across a page boundary we have a
2744	 * fault hazard.
2745	 */
2746	if ((((uintptr_t)(&hba_pkt->scsi_pkt)) & MMU_PAGEMASK) ==
2747	    (((uintptr_t)(&hba_pkt->pkt_wrapper_magic)) & MMU_PAGEMASK)) {
2748		/* fastpath, no cross-page hazard */
2749		magic = hba_pkt->pkt_wrapper_magic;
2750	} else {
2751		/* add protection for cross-page hazard */
2752		if (ddi_peek32((dev_info_t *)NULL,
2753		    &hba_pkt->pkt_wrapper_magic, &magic) == DDI_FAILURE) {
2754			return (0);	/* violation */
2755		}
2756	}
2757
2758	/* properly allocated packet always has correct magic */
2759	return ((magic == PKT_WRAPPER_MAGIC) ? 1 : 0);
2760}
2761
2762/*
2763 * Private interfaces to simplify conversion of legacy drivers so they don't
2764 * depend on scsi_*(9S) size. Instead of using these private interface, HBA
2765 * drivers should use DDI sanctioned allocation methods:
2766 *
2767 *	scsi_pkt	Use scsi_hba_pkt_alloc(9F), or implement
2768 *			tran_setup_pkt(9E).
2769 *
2770 *	scsi_device	You are doing something strange/special, a scsi_device
2771 *			structure should only be allocated by scsi_hba.c
2772 *			initchild code or scsi_vhci.c code.
2773 *
2774 *	scsi_hba_tran	Use scsi_hba_tran_alloc(9F).
2775 */
2776size_t
2777scsi_pkt_size()
2778{
2779	return (sizeof (struct scsi_pkt));
2780}
2781
2782size_t
2783scsi_hba_tran_size()
2784{
2785	return (sizeof (scsi_hba_tran_t));
2786}
2787
2788size_t
2789scsi_device_size()
2790{
2791	return (sizeof (struct scsi_device));
2792}
2793
2794/*
2795 * Legacy compliance to scsi_pkt(9S) allocation rules through use of
2796 * scsi_pkt_size() is detected by the 'scsi-size-clean' driver.conf property
2797 * or an HBA driver calling to scsi_size_clean() from attach(9E).  A driver
2798 * developer should only indicate that a legacy driver is clean after using
2799 * SCSI_SIZE_CLEAN_VERIFY to ensure compliance (see scsi_pkt.h).
2800 */
2801void
2802scsi_size_clean(dev_info_t *self)
2803{
2804	major_t		major;
2805	struct devnames	*dnp;
2806
2807	ASSERT(self);
2808	major = ddi_driver_major(self);
2809	ASSERT(major < devcnt);
2810	if (major >= devcnt) {
2811		SCSI_HBA_LOG((_LOG(WARN), self, NULL,
2812		    "scsi_pkt_size: bogus major: %d", major));
2813		return;
2814	}
2815
2816	/* Set DN_SCSI_SIZE_CLEAN flag in dn_flags. */
2817	dnp = &devnamesp[major];
2818	if ((dnp->dn_flags & DN_SCSI_SIZE_CLEAN) == 0) {
2819		LOCK_DEV_OPS(&dnp->dn_lock);
2820		dnp->dn_flags |= DN_SCSI_SIZE_CLEAN;
2821		UNLOCK_DEV_OPS(&dnp->dn_lock);
2822	}
2823}
2824
2825
2826/*
2827 * Called by an HBA to map strings to capability indices
2828 */
2829int
2830scsi_hba_lookup_capstr(
2831	char			*capstr)
2832{
2833	/*
2834	 * Capability strings: only add entries to mask the legacy
2835	 * '_' vs. '-' misery.  All new capabilities should use '-',
2836	 * and be captured be added to SCSI_CAP_ASCII.
2837	 */
2838	static struct cap_strings {
2839		char	*cap_string;
2840		int	cap_index;
2841	} cap_strings[] = {
2842		{ "dma_max",		SCSI_CAP_DMA_MAX		},
2843		{ "msg_out",		SCSI_CAP_MSG_OUT		},
2844		{ "wide_xfer",		SCSI_CAP_WIDE_XFER		},
2845		{ NULL,			0				}
2846	};
2847	static char		*cap_ascii[] = SCSI_CAP_ASCII;
2848	char			**cap;
2849	int			i;
2850	struct cap_strings	*cp;
2851
2852	for (cap = cap_ascii, i = 0; *cap != NULL; cap++, i++)
2853		if (strcmp(*cap, capstr) == 0)
2854			return (i);
2855
2856	for (cp = cap_strings; cp->cap_string != NULL; cp++)
2857		if (strcmp(cp->cap_string, capstr) == 0)
2858			return (cp->cap_index);
2859
2860	return (-1);
2861}
2862
2863/*
2864 * Called by an HBA to determine if the system is in 'panic' state.
2865 */
2866int
2867scsi_hba_in_panic()
2868{
2869	return (panicstr != NULL);
2870}
2871
2872/*
2873 * If a SCSI target driver attempts to mmap memory,
2874 * the buck stops here.
2875 */
2876/*ARGSUSED*/
2877static int
2878scsi_hba_map_fault(
2879	dev_info_t		*self,
2880	dev_info_t		*child,
2881	struct hat		*hat,
2882	struct seg		*seg,
2883	caddr_t			addr,
2884	struct devpage		*dp,
2885	pfn_t			pfn,
2886	uint_t			prot,
2887	uint_t			lock)
2888{
2889	return (DDI_FAILURE);
2890}
2891
2892static int
2893scsi_hba_get_eventcookie(
2894	dev_info_t		*self,
2895	dev_info_t		*child,
2896	char			*name,
2897	ddi_eventcookie_t	*eventp)
2898{
2899	scsi_hba_tran_t		*tran;
2900
2901	tran = ddi_get_driver_private(self);
2902	if (tran->tran_get_eventcookie &&
2903	    ((*tran->tran_get_eventcookie)(self,
2904	    child, name, eventp) == DDI_SUCCESS)) {
2905		return (DDI_SUCCESS);
2906	}
2907
2908	return (ndi_busop_get_eventcookie(self, child, name, eventp));
2909}
2910
2911static int
2912scsi_hba_add_eventcall(
2913	dev_info_t		*self,
2914	dev_info_t		*child,
2915	ddi_eventcookie_t	event,
2916	void			(*callback)(
2917					dev_info_t *self,
2918					ddi_eventcookie_t event,
2919					void *arg,
2920					void *bus_impldata),
2921	void			*arg,
2922	ddi_callback_id_t	*cb_id)
2923{
2924	scsi_hba_tran_t		*tran;
2925
2926	tran = ddi_get_driver_private(self);
2927	if (tran->tran_add_eventcall &&
2928	    ((*tran->tran_add_eventcall)(self, child,
2929	    event, callback, arg, cb_id) == DDI_SUCCESS)) {
2930		return (DDI_SUCCESS);
2931	}
2932
2933	return (DDI_FAILURE);
2934}
2935
2936static int
2937scsi_hba_remove_eventcall(dev_info_t *self, ddi_callback_id_t cb_id)
2938{
2939	scsi_hba_tran_t		*tran;
2940	ASSERT(cb_id);
2941
2942	tran = ddi_get_driver_private(self);
2943	if (tran->tran_remove_eventcall &&
2944	    ((*tran->tran_remove_eventcall)(
2945	    self, cb_id) == DDI_SUCCESS)) {
2946		return (DDI_SUCCESS);
2947	}
2948
2949	return (DDI_FAILURE);
2950}
2951
2952static int
2953scsi_hba_post_event(
2954	dev_info_t		*self,
2955	dev_info_t		*child,
2956	ddi_eventcookie_t	event,
2957	void			*bus_impldata)
2958{
2959	scsi_hba_tran_t		*tran;
2960
2961	tran = ddi_get_driver_private(self);
2962	if (tran->tran_post_event &&
2963	    ((*tran->tran_post_event)(self,
2964	    child, event, bus_impldata) == DDI_SUCCESS)) {
2965		return (DDI_SUCCESS);
2966	}
2967
2968	return (DDI_FAILURE);
2969}
2970
2971/*
2972 * Default getinfo(9e) for scsi_hba
2973 */
2974/* ARGSUSED */
2975static int
2976scsi_hba_info(dev_info_t *self, ddi_info_cmd_t infocmd, void *arg,
2977    void **result)
2978{
2979	int error = DDI_SUCCESS;
2980
2981	switch (infocmd) {
2982	case DDI_INFO_DEVT2INSTANCE:
2983		*result = (void *)(intptr_t)(MINOR2INST(getminor((dev_t)arg)));
2984		break;
2985	default:
2986		error = DDI_FAILURE;
2987	}
2988	return (error);
2989}
2990
2991/*
2992 * Default open and close routine for scsi_hba
2993 */
2994/* ARGSUSED */
2995int
2996scsi_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
2997{
2998	dev_info_t	*self;
2999	scsi_hba_tran_t	*tran;
3000	int		rv = 0;
3001
3002	if (otyp != OTYP_CHR)
3003		return (EINVAL);
3004
3005	if ((self = e_ddi_hold_devi_by_dev(*devp, 0)) == NULL)
3006		return (ENXIO);
3007
3008	tran = ddi_get_driver_private(self);
3009	if (tran == NULL) {
3010		ddi_release_devi(self);
3011		return (ENXIO);
3012	}
3013
3014	/*
3015	 * tran_open_flag bit field:
3016	 *	0:	closed
3017	 *	1:	shared open by minor at bit position
3018	 *	1 at 31st bit:	exclusive open
3019	 */
3020	mutex_enter(&(tran->tran_open_lock));
3021	if (flags & FEXCL) {
3022		if (tran->tran_open_flag != 0) {
3023			rv = EBUSY;		/* already open */
3024		} else {
3025			tran->tran_open_flag = TRAN_OPEN_EXCL;
3026		}
3027	} else {
3028		if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
3029			rv = EBUSY;		/* already excl. open */
3030		} else {
3031			int minor = getminor(*devp) & TRAN_MINOR_MASK;
3032			tran->tran_open_flag |= (1 << minor);
3033			/*
3034			 * Ensure that the last framework reserved minor
3035			 * is unused. Otherwise, the exclusive open
3036			 * mechanism may break.
3037			 */
3038			ASSERT(minor != 31);
3039		}
3040	}
3041	mutex_exit(&(tran->tran_open_lock));
3042
3043	ddi_release_devi(self);
3044	return (rv);
3045}
3046
3047/* ARGSUSED */
3048int
3049scsi_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
3050{
3051	dev_info_t	*self;
3052	scsi_hba_tran_t	*tran;
3053
3054	if (otyp != OTYP_CHR)
3055		return (EINVAL);
3056
3057	if ((self = e_ddi_hold_devi_by_dev(dev, 0)) == NULL)
3058		return (ENXIO);
3059
3060	tran = ddi_get_driver_private(self);
3061	if (tran == NULL) {
3062		ddi_release_devi(self);
3063		return (ENXIO);
3064	}
3065
3066	mutex_enter(&(tran->tran_open_lock));
3067	if (tran->tran_open_flag == TRAN_OPEN_EXCL) {
3068		tran->tran_open_flag = 0;
3069	} else {
3070		int minor = getminor(dev) & TRAN_MINOR_MASK;
3071		tran->tran_open_flag &= ~(1 << minor);
3072	}
3073	mutex_exit(&(tran->tran_open_lock));
3074
3075	ddi_release_devi(self);
3076	return (0);
3077}
3078
3079/*
3080 * standard ioctl commands for SCSI hotplugging
3081 */
3082/* ARGSUSED */
3083int
3084scsi_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
3085    int *rvalp)
3086{
3087	dev_info_t		*self;
3088	struct devctl_iocdata	*dcp = NULL;
3089	dev_info_t		*child = NULL;
3090	mdi_pathinfo_t		*path = NULL;
3091	struct scsi_device	*sd;
3092	scsi_hba_tran_t		*tran;
3093	uint_t			bus_state;
3094	int			rv = 0;
3095	int			circ;
3096	char			*name;
3097	char			*addr;
3098
3099	self = e_ddi_hold_devi_by_dev(dev, 0);
3100	if (self == NULL) {
3101		rv = ENXIO;
3102		goto out;
3103	}
3104
3105	tran = ddi_get_driver_private(self);
3106	if (tran == NULL) {
3107		rv = ENXIO;
3108		goto out;
3109	}
3110
3111	/* Ioctls for which the generic implementation suffices. */
3112	switch (cmd) {
3113	case DEVCTL_BUS_GETSTATE:
3114		rv = ndi_devctl_ioctl(self, cmd, arg, mode, 0);
3115		goto out;
3116	}
3117
3118	/* read devctl ioctl data */
3119	if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS) {
3120		rv = EFAULT;
3121		goto out;
3122	}
3123
3124	/* Ioctls that require child identification */
3125	switch (cmd) {
3126	case DEVCTL_DEVICE_GETSTATE:
3127	case DEVCTL_DEVICE_ONLINE:
3128	case DEVCTL_DEVICE_OFFLINE:
3129	case DEVCTL_DEVICE_REMOVE:
3130	case DEVCTL_DEVICE_RESET:
3131		name = ndi_dc_getname(dcp);
3132		addr = ndi_dc_getaddr(dcp);
3133		if ((name == NULL) || (addr == NULL)) {
3134			rv = EINVAL;
3135			goto out;
3136		}
3137
3138		/*
3139		 * Find child with name@addr - might find a devinfo
3140		 * child (child), a pathinfo child (path), or nothing.
3141		 */
3142		scsi_hba_devi_enter(self, &circ);
3143
3144		(void) scsi_findchild(self, name, addr, 1, &child, &path, NULL);
3145		if (path) {
3146			/* Found a pathinfo */
3147			ASSERT(path && (child == NULL));
3148			mdi_hold_path(path);
3149			scsi_hba_devi_exit_phci(self, circ);
3150			sd = NULL;
3151		} else if (child) {
3152			/* Found a devinfo */
3153			ASSERT(child && (path == NULL));
3154
3155			/* verify scsi_device of child */
3156			if (ndi_flavor_get(child) == SCSA_FLAVOR_SCSI_DEVICE)
3157				sd = ddi_get_driver_private(child);
3158			else
3159				sd = NULL;
3160		} else {
3161			ASSERT((path == NULL) && (child == NULL));
3162			scsi_hba_devi_exit(self, circ);
3163			rv = ENXIO;			/* found nothing */
3164			goto out;
3165		}
3166		break;
3167
3168	case DEVCTL_BUS_RESETALL:	/* ioctl that operate on any child */
3169		/*
3170		 * Find a child's scsi_address so we can invoke tran_reset.
3171		 *
3172		 * Future: If no child exists, we could fake a child. This will
3173		 * be a enhancement for the future - for now, we fall back to
3174		 * BUS_RESET.
3175		 */
3176		scsi_hba_devi_enter(self, &circ);
3177		child = ddi_get_child(self);
3178		sd = NULL;
3179		while (child) {
3180			/* verify scsi_device of child */
3181			if (ndi_flavor_get(child) == SCSA_FLAVOR_SCSI_DEVICE)
3182				sd = ddi_get_driver_private(child);
3183			if (sd != NULL) {
3184				/*
3185				 * NOTE: node has a scsi_device structure, so
3186				 * it must be initialized.
3187				 */
3188				ndi_hold_devi(child);
3189				break;
3190			}
3191			child = ddi_get_next_sibling(child);
3192		}
3193		scsi_hba_devi_exit(self, circ);
3194		break;
3195	}
3196
3197	switch (cmd) {
3198	case DEVCTL_DEVICE_GETSTATE:
3199		if (path) {
3200			if (mdi_dc_return_dev_state(path, dcp) != MDI_SUCCESS)
3201				rv = EFAULT;
3202		} else if (child) {
3203			if (ndi_dc_return_dev_state(child, dcp) != NDI_SUCCESS)
3204				rv = EFAULT;
3205		} else {
3206			rv = ENXIO;
3207		}
3208		break;
3209
3210	case DEVCTL_DEVICE_RESET:
3211		if (sd == NULL) {
3212			rv = ENOTTY;
3213			break;
3214		}
3215		if (tran->tran_reset == NULL) {
3216			rv = ENOTSUP;
3217			break;
3218		}
3219
3220		/* Start with the small stick */
3221		if (scsi_reset(&sd->sd_address, RESET_LUN) == 1)
3222			break;		/* LUN reset worked */
3223		if (scsi_reset(&sd->sd_address, RESET_TARGET) != 1)
3224			rv = EIO;	/* Target reset failed */
3225		break;
3226
3227	case DEVCTL_BUS_QUIESCE:
3228		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
3229		    (bus_state == BUS_QUIESCED))
3230			rv = EALREADY;
3231		else if (tran->tran_quiesce == NULL)
3232			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3233		else if (tran->tran_quiesce(self) != 0)
3234			rv = EIO;
3235		else if (ndi_set_bus_state(self, BUS_QUIESCED) != NDI_SUCCESS)
3236			rv = EIO;
3237		break;
3238
3239	case DEVCTL_BUS_UNQUIESCE:
3240		if ((ndi_get_bus_state(self, &bus_state) == NDI_SUCCESS) &&
3241		    (bus_state == BUS_ACTIVE))
3242			rv = EALREADY;
3243		else if (tran->tran_unquiesce == NULL)
3244			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3245		else if (tran->tran_unquiesce(self) != 0)
3246			rv = EIO;
3247		else if (ndi_set_bus_state(self, BUS_ACTIVE) != NDI_SUCCESS)
3248			rv = EIO;
3249		break;
3250
3251	case DEVCTL_BUS_RESET:
3252		if (tran->tran_bus_reset == NULL)
3253			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3254		else if (tran->tran_bus_reset(self, RESET_BUS) != 1)
3255			rv = EIO;
3256		break;
3257
3258	case DEVCTL_BUS_RESETALL:
3259		if ((sd != NULL) &&
3260		    (scsi_reset(&sd->sd_address, RESET_ALL) == 1)) {
3261			break;		/* reset all worked */
3262		}
3263		if (tran->tran_bus_reset == NULL) {
3264			rv = ENOTSUP; /* man ioctl(7I) says ENOTTY */
3265			break;
3266		}
3267		if (tran->tran_bus_reset(self, RESET_BUS) != 1)
3268			rv = EIO;	/* bus reset failed */
3269		break;
3270
3271	case DEVCTL_BUS_CONFIGURE:
3272		if (ndi_devi_config(self, NDI_DEVFS_CLEAN | NDI_DEVI_PERSIST |
3273		    NDI_CONFIG_REPROBE) != NDI_SUCCESS) {
3274			rv = EIO;
3275		}
3276		break;
3277
3278	case DEVCTL_BUS_UNCONFIGURE:
3279		if (ndi_devi_unconfig(self,
3280		    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) != NDI_SUCCESS) {
3281			rv = EBUSY;
3282		}
3283		break;
3284
3285	case DEVCTL_DEVICE_ONLINE:
3286		ASSERT(child || path);
3287		if (path) {
3288			if (mdi_pi_online(path, NDI_USER_REQ) != MDI_SUCCESS)
3289				rv = EIO;
3290		} else {
3291			if (ndi_devi_online(child, 0) != NDI_SUCCESS)
3292				rv = EIO;
3293		}
3294		break;
3295
3296	case DEVCTL_DEVICE_OFFLINE:
3297		ASSERT(child || path);
3298		if (sd != NULL)
3299			(void) scsi_clear_task_set(&sd->sd_address);
3300		if (path) {
3301			if (mdi_pi_offline(path, NDI_USER_REQ) != MDI_SUCCESS)
3302				rv = EIO;
3303		} else {
3304			if (ndi_devi_offline(child,
3305			    NDI_DEVFS_CLEAN) != NDI_SUCCESS)
3306				rv = EIO;
3307		}
3308		break;
3309
3310	case DEVCTL_DEVICE_REMOVE:
3311		ASSERT(child || path);
3312		if (sd != NULL)
3313			(void) scsi_clear_task_set(&sd->sd_address);
3314		if (path) {
3315			/* NOTE: don't pass NDI_DEVI_REMOVE to mdi_pi_offline */
3316			if (mdi_pi_offline(path, NDI_USER_REQ) == MDI_SUCCESS) {
3317				scsi_hba_devi_enter_phci(self, &circ);
3318				mdi_rele_path(path);
3319
3320				/* ... here is the DEVICE_REMOVE part. */
3321				(void) mdi_pi_free(path, 0);
3322				path = NULL;
3323			} else {
3324				rv = EIO;
3325			}
3326		} else {
3327			if (ndi_devi_offline(child,
3328			    NDI_DEVFS_CLEAN | NDI_DEVI_REMOVE) != NDI_SUCCESS)
3329				rv = EIO;
3330		}
3331		break;
3332
3333	default:
3334		ASSERT(dcp != NULL);
3335		rv = ENOTTY;
3336		break;
3337	}
3338
3339	/* all done -- clean up and return */
3340out:
3341	/* release hold on what we found */
3342	if (path) {
3343		scsi_hba_devi_enter_phci(self, &circ);
3344		mdi_rele_path(path);
3345	}
3346	if (path || child)
3347		scsi_hba_devi_exit(self, circ);
3348
3349	if (dcp)
3350		ndi_dc_freehdl(dcp);
3351
3352	if (self)
3353		ddi_release_devi(self);
3354
3355	*rvalp = rv;
3356
3357	return (rv);
3358}
3359
3360/*ARGSUSED*/
3361static int
3362scsi_hba_fm_init_child(dev_info_t *self, dev_info_t *child, int cap,
3363    ddi_iblock_cookie_t *ibc)
3364{
3365	scsi_hba_tran_t	*tran = ddi_get_driver_private(self);
3366
3367	return (tran ? tran->tran_fm_capable : scsi_fm_capable);
3368}
3369
3370static int
3371scsi_hba_bus_power(dev_info_t *self, void *impl_arg, pm_bus_power_op_t op,
3372    void *arg, void *result)
3373{
3374	scsi_hba_tran_t	*tran;
3375
3376	tran = ddi_get_driver_private(self);
3377	if (tran && tran->tran_bus_power) {
3378		return (tran->tran_bus_power(self, impl_arg,
3379		    op, arg, result));
3380	}
3381
3382	return (pm_busop_bus_power(self, impl_arg, op, arg, result));
3383}
3384
3385/*
3386 * Return the lun64 value from a address string: "addr,lun[,sfunc]". Either
3387 * the lun is after the first ',' or the entire address string is the lun.
3388 * Return SCSI_LUN64_ILLEGAL if the format is incorrect. A lun64 is at most
3389 * 16 hex digits long.
3390 *
3391 * If the address string specified has incorrect syntax (busconfig one of
3392 * bogus /devices path) then scsi_addr_to_lun64 can return SCSI_LUN64_ILLEGAL.
3393 */
3394static scsi_lun64_t
3395scsi_addr_to_lun64(char *addr)
3396{
3397	scsi_lun64_t	lun64;
3398	char		*s;
3399	int		i;
3400
3401	if (addr) {
3402		s = strchr(addr, ',');			/* "addr,lun" */
3403		if (s)
3404			s++;				/* skip ',', at lun */
3405		else
3406			s = addr;			/* "lun" */
3407
3408		for (lun64 = 0, i = 0; *s && (i < 16); s++, i++) {
3409			if (*s >= '0' && *s <= '9')
3410				lun64 = (lun64 << 4) + (*s - '0');
3411			else if (*s >= 'A' && *s <= 'F')
3412				lun64 = (lun64 << 4) + 10 + (*s - 'A');
3413			else if (*s >= 'a' && *s <= 'f')
3414				lun64 = (lun64 << 4) + 10 + (*s - 'a');
3415			else
3416				break;
3417		}
3418		if (*s && (*s != ','))		/* [,sfunc] is OK */
3419			lun64 = SCSI_LUN64_ILLEGAL;
3420	} else
3421		lun64 = SCSI_LUN64_ILLEGAL;
3422
3423	if (lun64 == SCSI_LUN64_ILLEGAL)
3424		SCSI_HBA_LOG((_LOG(2), NULL, NULL,
3425		    "addr_to_lun64 %s lun %" PRIlun64,
3426		    addr ? addr : "NULL", lun64));
3427	return (lun64);
3428}
3429
3430/*
3431 * Return the sfunc value from a address string: "addr,lun[,sfunc]". Either the
3432 * sfunc is after the second ',' or the entire address string is the sfunc.
3433 * Return -1 if there is only one ',' in the address string or the string is
3434 * invalid. An sfunc is at most two hex digits long.
3435 */
3436static int
3437scsi_addr_to_sfunc(char *addr)
3438{
3439	int		sfunc;
3440	char		*s;
3441	int		i;
3442
3443	if (addr) {
3444		s = strchr(addr, ',');			/* "addr,lun" */
3445		if (s) {
3446			s++;				/* skip ',', at lun */
3447			s = strchr(s, ',');		/* "lun,sfunc" */
3448			if (s == NULL)
3449				return (-1);		/* no ",sfunc" */
3450			s++;				/* skip ',', at sfunc */
3451		} else
3452			s = addr;			/* "sfunc" */
3453
3454		for (sfunc = 0, i = 0; *s && (i < 2); s++, i++) {
3455			if (*s >= '0' && *s <= '9')
3456				sfunc = (sfunc << 4) + (*s - '0');
3457			else if (*s >= 'A' && *s <= 'F')
3458				sfunc = (sfunc << 4) + 10 + (*s - 'A');
3459			else if (*s >= 'a' && *s <= 'f')
3460				sfunc = (sfunc << 4) + 10 + (*s - 'a');
3461			else
3462				break;
3463		}
3464		if (*s)
3465			sfunc = -1;			/* illegal */
3466	} else
3467		sfunc = -1;
3468	return (sfunc);
3469}
3470
3471/*
3472 * Convert scsi ascii string data to NULL terminated (semi) legal IEEE 1275
3473 * "compatible" (name) property form.
3474 *
3475 * For ASCII INQUIRY data, a one-way conversion algorithm is needed to take
3476 * SCSI_ASCII (20h - 7Eh) to a 1275-like compatible form. The 1275 spec allows
3477 * letters, digits, one ",", and ". _ + -", all limited by a maximum 31
3478 * character length. Since ", ." are used as separators in the compatible
3479 * string itself, they are converted to "_". All SCSI_ASCII characters that
3480 * are illegal in 1275, as well as any illegal SCSI_ASCII characters
3481 * encountered, are converted to "_". To reduce length, trailing blanks are
3482 * trimmed from SCSI_ASCII fields prior to conversion.
3483 *
3484 * Example: SCSI_ASCII "ST32550W SUN2.1G" -> "ST32550W_SUN2_1G"
3485 *
3486 * NOTE: the 1275 string form is always less than or equal to the scsi form.
3487 */
3488static char *
3489string_scsi_to_1275(char *s_1275, char *s_scsi, int len)
3490{
3491	(void) strncpy(s_1275, s_scsi, len);
3492	s_1275[len--] = '\0';
3493
3494	while (len >= 0) {
3495		if (s_1275[len] == ' ')
3496			s_1275[len--] = '\0';	/* trim trailing " " */
3497		else
3498			break;
3499	}
3500
3501	while (len >= 0) {
3502		if (((s_1275[len] >= 'a') && (s_1275[len] <= 'z')) ||
3503		    ((s_1275[len] >= 'A') && (s_1275[len] <= 'Z')) ||
3504		    ((s_1275[len] >= '0') && (s_1275[len] <= '9')) ||
3505		    (s_1275[len] == '_') ||
3506		    (s_1275[len] == '+') ||
3507		    (s_1275[len] == '-'))
3508			len--;			/* legal 1275  */
3509		else
3510			s_1275[len--] = '_';	/* illegal SCSI_ASCII | 1275 */
3511	}
3512
3513	return (s_1275);
3514}
3515
3516/*
3517 * Given the inquiry data, binding_set, and dtype_node for a scsi device,
3518 * return the nodename and compatible property for the device. The "compatible"
3519 * concept comes from IEEE-1275. The compatible information is returned is in
3520 * the correct form for direct use defining the "compatible" string array
3521 * property. Internally, "compatible" is also used to determine the nodename
3522 * to return.
3523 *
3524 * This function is provided as a separate entry point for use by drivers that
3525 * currently issue their own non-SCSA inquiry command and perform their own
3526 * node creation based their own private compiled in tables. Converting these
3527 * drivers to use this interface provides a quick easy way of obtaining
3528 * consistency as well as the flexibility associated with the 1275 techniques.
3529 *
3530 * The dtype_node is passed as a separate argument (instead of having the
3531 * implementation use inq_dtype). It indicates that information about
3532 * a secondary function embedded service should be produced.
3533 *
3534 * Callers must always use scsi_hba_nodename_compatible_free, even if
3535 * *nodenamep is null, to free the nodename and compatible information
3536 * when done.
3537 *
3538 * If a nodename can't be determined then **compatiblep will point to a
3539 * diagnostic string containing all the compatible forms.
3540 *
3541 * NOTE: some compatible strings may violate the 31 character restriction
3542 * imposed by IEEE-1275. This is not a problem because Solaris does not care
3543 * about this 31 character limit.
3544 *
3545 * Each compatible form belongs to a form-group.  The form-groups currently
3546 * defined are generic ("scsiclass"), binding-set ("scsa.b"), and failover
3547 * ("scsa.f").
3548 *
3549 * The following compatible forms, in high to low precedence
3550 * order, are defined for SCSI target device nodes.
3551 *
3552 *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(1 *1&2)
3553 *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(2 *1)
3554 *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(3 *2)
3555 *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR	(4)
3556 *  scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP	(5 *1&2)
3557 *  scsiclass,DDEE.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(6 *1)
3558 *  scsiclass,DDFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(7 *2)
3559 *  scsiclass,DD.vVVVVVVVV.pPPPPPPPPPPPPPPPP		(8)
3560 *  scsa,DD.bBBBBBBBB					(8.5 *3)
3561 *  scsiclass,DDEEFFF					(9 *1&2)
3562 *  scsiclass,DDEE					(10 *1)
3563 *  scsiclass,DDFFF					(11 *2)
3564 *  scsiclass,DD					(12)
3565 *  scsa.fFFF						(12.5 *4)
3566 *  scsiclass						(13)
3567 *
3568 *	  *1 only produced on a secondary function node
3569 *	  *2 only produced when generic form-group flags exist.
3570 *	  *3 only produced when binding-set form-group legacy support is needed
3571 *	  *4 only produced when failover form-group flags exist.
3572 *
3573 *	where:
3574 *
3575 *	v			is the letter 'v'. Denotest the
3576 *				beginning of VVVVVVVV.
3577 *
3578 *	VVVVVVVV		Translated scsi_vendor.
3579 *
3580 *	p			is the letter 'p'. Denotes the
3581 *				beginning of PPPPPPPPPPPPPPPP.
3582 *
3583 *	PPPPPPPPPPPPPPPP	Translated scsi_product.
3584 *
3585 *	r			is the letter 'r'. Denotes the
3586 *				beginning of RRRR.
3587 *
3588 *	RRRR			Translated scsi_revision.
3589 *
3590 *	DD			is a two digit ASCII hexadecimal
3591 *				number. The value of the two digits is
3592 *				based one the SCSI "Peripheral device
3593 *				type" command set associated with the
3594 *				node. On a primary node this is the
3595 *				scsi_dtype of the primary command set,
3596 *				on a secondary node this is the
3597 *				scsi_dtype associated with the secondary
3598 *				function embedded command set.
3599 *
3600 *	EE			Same encoding used for DD. This form is
3601 *				only generated on secondary function
3602 *				nodes. The DD secondary function is embedded
3603 *				in an EE device.
3604 *
3605 *	FFF			Concatenation, in alphabetical order,
3606 *				of the flag characters within a form-group.
3607 *				For a given form-group, the following
3608 *				flags are defined.
3609 *
3610 *				scsiclass: (generic form-group):
3611 *				  R	Removable_Media: Used when
3612 *					inq_rmb is set.
3613 *				  S	SAF-TE device: Used when
3614 *					inquiry information indicates
3615 *					SAF-TE devices.
3616 *
3617 *				scsa.f:	(failover form-group):
3618 *				  E	Explicit Target_Port_Group: Used
3619 *					when inq_tpgse is set and 'G' is
3620 *					alse present.
3621 *				  G	GUID: Used when a GUID can be
3622 *					generated for the device.
3623 *				  I	Implicit Target_Port_Group: Used
3624 *					when inq_tpgs is set and 'G' is
3625 *					also present.
3626 *
3627 *				Forms using FFF are only be generated
3628 *				if there are applicable flag
3629 *				characters.
3630 *
3631 *	b			is the letter 'b'. Denotes the
3632 *				beginning of BBBBBBBB.
3633 *
3634 *	BBBBBBBB		Binding-set. Operating System Specific:
3635 *				scsi-binding-set property of HBA.
3636 */
3637#define	NCOMPAT		(1 + (13 + 2) + 1)
3638#define	COMPAT_LONGEST	(strlen( \
3639	"scsiclass,DDEEFFF.vVVVVVVVV.pPPPPPPPPPPPPPPPP.rRRRR" + 1))
3640
3641/*
3642 * Private version with extra device 'identity' arguments to allow code
3643 * to determine GUID FFF support.
3644 */
3645static void
3646scsi_hba_ident_nodename_compatible_get(struct scsi_inquiry *inq,
3647    uchar_t *inq80, size_t inq80len, uchar_t *inq83, size_t inq83len,
3648    char *binding_set, int dtype_node, char *compat0,
3649    char **nodenamep, char **drivernamep,
3650    char ***compatiblep, int *ncompatiblep)
3651{
3652	char		vid[sizeof (inq->inq_vid) + 1 ];
3653	char		pid[sizeof (inq->inq_pid) + 1];
3654	char		rev[sizeof (inq->inq_revision) + 1];
3655	char		gf[sizeof ("RS\0")];
3656	char		ff[sizeof ("EGI\0")];
3657	int		dtype_device;
3658	int		ncompat;		/* number of compatible */
3659	char		**compatp;		/* compatible ptrs */
3660	int		i;
3661	char		*nname;			/* nodename */
3662	char		*dname;			/* driver name */
3663	char		**csp;
3664	char		*p;
3665	int		tlen;
3666	int		len;
3667	major_t		major;
3668	ddi_devid_t	devid;
3669	char		*guid;
3670	uchar_t		*iqd = (uchar_t *)inq;
3671
3672	/*
3673	 * Nodename_aliases: This table was originally designed to be
3674	 * implemented via a new nodename_aliases file - a peer to the
3675	 * driver_aliases that selects a nodename based on compatible
3676	 * forms in much the same say driver_aliases is used to select
3677	 * driver bindings from compatible forms. Each compatible form
3678	 * is an 'alias'. Until a more general need for a
3679	 * nodename_aliases file exists, which may never occur, the
3680	 * scsi mappings are described here via a compiled in table.
3681	 *
3682	 * This table contains nodename mappings for self-identifying
3683	 * scsi devices enumerated by the Solaris kernel. For a given
3684	 * device, the highest precedence "compatible" form with a
3685	 * mapping is used to select the nodename for the device. This
3686	 * will typically be a generic nodename, however in some legacy
3687	 * compatibility cases a driver nodename mapping may be selected.
3688	 *
3689	 * Because of possible breakage associated with switching SCSI
3690	 * target devices from driver nodenames to generic nodenames,
3691	 * we are currently unable to support generic nodenames for all
3692	 * SCSI devices (binding-sets). Although /devices paths are
3693	 * defined as unstable, avoiding possible breakage is
3694	 * important. Some of the newer SCSI transports (USB) already
3695	 * use generic nodenames. All new SCSI transports and target
3696	 * devices should use generic nodenames. At times this decision
3697	 * may be architecture dependent (sparc .vs. intel) based on when
3698	 * a transport was supported on a particular architecture.
3699	 *
3700	 * We provide a base set of generic nodename mappings based on
3701	 * scsiclass dtype and higher-precedence driver nodename
3702	 * mappings based on scsa "binding-set" to cover legacy
3703	 * issues. The binding-set is typically associated with
3704	 * "scsi-binding-set" property value of the HBA. The legacy
3705	 * mappings are provided independent of whether the driver they
3706	 * refer to is installed. This allows a correctly named node
3707	 * be created at discovery time, and binding to occur when/if
3708	 * an add_drv of the legacy driver occurs.
3709	 *
3710	 * We also have mappings for legacy SUN hardware that
3711	 * misidentifies itself (enclosure services which identify
3712	 * themselves as processors). All future hardware should use
3713	 * the correct dtype.
3714	 *
3715	 * As SCSI HBAs are modified to use the SCSA interfaces for
3716	 * self-identifying SCSI target devices (PSARC/2004/116) the
3717	 * nodename_aliases table (PSARC/2004/420) should be augmented
3718	 * with legacy mappings in order to maintain compatibility with
3719	 * existing /devices paths, especially for devices that house
3720	 * an OS. Failure to do this may cause upgrade problems.
3721	 * Additions for new target devices or transports should not
3722	 * add scsa binding-set compatible mappings.
3723	 */
3724	static struct nodename_aliases {
3725		char	*na_nodename;		/* nodename */
3726		char	*na_alias;		/* compatible form match */
3727	} na[] = {
3728	/* # mapping to generic nodenames based on scsi dtype */
3729		{"disk",		"scsiclass,00"},
3730		{"tape",		"scsiclass,01"},
3731		{"printer",		"scsiclass,02"},
3732		{"processor",		"scsiclass,03"},
3733		{"worm",		"scsiclass,04"},
3734		{"cdrom",		"scsiclass,05"},
3735		{"scanner",		"scsiclass,06"},
3736		{"optical-disk",	"scsiclass,07"},
3737		{"medium-changer",	"scsiclass,08"},
3738		{"obsolete",		"scsiclass,09"},
3739		{"prepress-a",		"scsiclass,0a"},
3740		{"prepress-b",		"scsiclass,0b"},
3741		{"array-controller",	"scsiclass,0c"},
3742		{"enclosure",		"scsiclass,0d"},
3743		{"disk",		"scsiclass,0e"},
3744		{"card-reader",		"scsiclass,0f"},
3745		{"bridge",		"scsiclass,10"},
3746		{"object-store",	"scsiclass,11"},
3747		{"reserved",		"scsiclass,12"},
3748		{"reserved",		"scsiclass,13"},
3749		{"reserved",		"scsiclass,14"},
3750		{"reserved",		"scsiclass,15"},
3751		{"reserved",		"scsiclass,16"},
3752		{"reserved",		"scsiclass,17"},
3753		{"reserved",		"scsiclass,18"},
3754		{"reserved",		"scsiclass,19"},
3755		{"reserved",		"scsiclass,1a"},
3756		{"reserved",		"scsiclass,1b"},
3757		{"reserved",		"scsiclass,1c"},
3758		{"reserved",		"scsiclass,1d"},
3759		{"well-known-lun",	"scsiclass,1e"},
3760		{"unknown",		"scsiclass,1f"},
3761
3762#ifdef	sparc
3763	/* # legacy mapping to driver nodenames for fcp binding-set */
3764		{"ssd",			"scsa,00.bfcp"},
3765		{"st",			"scsa,01.bfcp"},
3766		{"sgen",		"scsa,08.bfcp"},
3767		{"ses",			"scsa,0d.bfcp"},
3768
3769	/* # legacy mapping to driver nodenames for vhci binding-set */
3770		{"ssd",			"scsa,00.bvhci"},
3771		{"st",			"scsa,01.bvhci"},
3772		{"sgen",		"scsa,08.bvhci"},
3773		{"ses",			"scsa,0d.bvhci"},
3774#else	/* sparc */
3775	/* # for x86 fcp and vhci use generic nodenames */
3776#endif	/* sparc */
3777
3778	/* # legacy mapping to driver nodenames for spi binding-set */
3779		{"sd",			"scsa,00.bspi"},
3780		{"sd",			"scsa,05.bspi"},
3781		{"sd",			"scsa,07.bspi"},
3782		{"st",			"scsa,01.bspi"},
3783		{"ses",			"scsa,0d.bspi"},
3784
3785	/* #				SUN misidentified spi hardware */
3786		{"ses",			"scsiclass,03.vSUN.pD2"},
3787		{"ses",			"scsiclass,03.vSYMBIOS.pD1000"},
3788
3789	/* # legacy mapping to driver nodenames for atapi binding-set */
3790		{"sd",			"scsa,00.batapi"},
3791		{"sd",			"scsa,05.batapi"},
3792		{"sd",			"scsa,07.batapi"},
3793		{"st",			"scsa,01.batapi"},
3794		{"unknown",		"scsa,0d.batapi"},
3795
3796	/* # legacy mapping to generic nodenames for usb binding-set */
3797		{"disk",		"scsa,05.busb"},
3798		{"disk",		"scsa,07.busb"},
3799		{"changer",		"scsa,08.busb"},
3800		{"comm",		"scsa,09.busb"},
3801		{"array_ctlr",		"scsa,0c.busb"},
3802		{"esi",			"scsa,0d.busb"},
3803
3804	/*
3805	 * mapping nodenames for mpt based on scsi dtype
3806	 * for being compatible with the original node names
3807	 * under mpt controller
3808	 */
3809		{"sd",			"scsa,00.bmpt"},
3810		{"sd",			"scsa,05.bmpt"},
3811		{"sd",			"scsa,07.bmpt"},
3812		{"st",			"scsa,01.bmpt"},
3813		{"ses",			"scsa,0d.bmpt"},
3814		{"sgen",		"scsa,08.bmpt"},
3815		{NULL,		NULL}
3816	};
3817	struct nodename_aliases *nap;
3818
3819	/* NOTE: drivernamep can be NULL */
3820	ASSERT(nodenamep && compatiblep && ncompatiblep &&
3821	    (binding_set == NULL || (strlen(binding_set) <= 8)));
3822	if ((nodenamep == NULL) || (compatiblep == NULL) ||
3823	    (ncompatiblep == NULL))
3824		return;
3825
3826	/*
3827	 * In order to reduce runtime we allocate one block of memory that
3828	 * contains both the NULL terminated array of pointers to compatible
3829	 * forms and the individual compatible strings. This block is
3830	 * somewhat larger than needed, but is short lived - it only exists
3831	 * until the caller can transfer the information into the "compatible"
3832	 * string array property and call scsi_hba_nodename_compatible_free.
3833	 */
3834	tlen = NCOMPAT * COMPAT_LONGEST;
3835	compatp = kmem_alloc((NCOMPAT * sizeof (char *)) + tlen, KM_SLEEP);
3836
3837	/* convert inquiry data from SCSI ASCII to 1275 string */
3838	(void) string_scsi_to_1275(vid, inq->inq_vid,
3839	    sizeof (inq->inq_vid));
3840	(void) string_scsi_to_1275(pid, inq->inq_pid,
3841	    sizeof (inq->inq_pid));
3842	(void) string_scsi_to_1275(rev, inq->inq_revision,
3843	    sizeof (inq->inq_revision));
3844	ASSERT((strlen(vid) <= sizeof (inq->inq_vid)) &&
3845	    (strlen(pid) <= sizeof (inq->inq_pid)) &&
3846	    (strlen(rev) <= sizeof (inq->inq_revision)));
3847
3848	/*
3849	 * Form flags in ***ALPHABETICAL*** order within form-group:
3850	 *
3851	 * NOTE: When adding a new flag to an existing form-group, careful
3852	 * consideration must be given to not breaking existing bindings
3853	 * based on that form-group.
3854	 */
3855
3856	/*
3857	 * generic form-group flags
3858	 *   R	removable:
3859	 *	Set when inq_rmb is set and for well known scsi dtypes. For a
3860	 *	bus where the entire device is removable (like USB), we expect
3861	 *	the HBA to intercept the inquiry data and set inq_rmb.
3862	 *	Since OBP does not distinguish removable media in its generic
3863	 *	name selection we avoid setting the 'R' flag if the root is not
3864	 *	yet mounted.
3865	 *   S	SAF-TE device
3866	 *	Set when the device type is SAT-TE.
3867	 */
3868	i = 0;
3869	dtype_device = inq->inq_dtype & DTYPE_MASK;
3870	if (modrootloaded && (inq->inq_rmb ||
3871	    (dtype_device == DTYPE_WORM) ||
3872	    (dtype_device == DTYPE_RODIRECT) ||
3873	    (dtype_device == DTYPE_OPTICAL)))
3874		gf[i++] = 'R';			/* removable */
3875	gf[i] = '\0';
3876
3877	if (modrootloaded &&
3878	    (dtype_device == DTYPE_PROCESSOR) &&
3879	    (strncmp((char *)&iqd[44], "SAF-TE", 4) == 0))
3880		gf[i++] = 'S';
3881	gf[i] = '\0';
3882
3883	/*
3884	 * failover form-group flags
3885	 *   E	Explicit Target_Port_Group_Supported:
3886	 *	Set for a device that has a GUID if inq_tpgse also set.
3887	 *   G	GUID:
3888	 *	Set when we have identity information, can determine a devid
3889	 *	from the identity information, and can generate a guid from
3890	 *	that devid.
3891	 *   I	Implicit Target_Port_Group_Supported:
3892	 *	Set for a device that has a GUID if inq_tpgs also set.
3893	 */
3894	i = 0;
3895	if ((inq80 || inq83) &&
3896	    (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST, NULL,
3897	    (uchar_t *)inq, sizeof (*inq), inq80, inq80len, inq83, inq83len,
3898	    &devid) == DDI_SUCCESS)) {
3899		guid = ddi_devid_to_guid(devid);
3900		ddi_devid_free(devid);
3901	} else
3902		guid = NULL;
3903	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_EXPLICIT))
3904		ff[i++] = 'E';			/* EXPLICIT TPGS */
3905	if (guid)
3906		ff[i++] = 'G';			/* GUID */
3907	if (guid && (inq->inq_tpgs & TPGS_FAILOVER_IMPLICIT))
3908		ff[i++] = 'I';			/* IMPLICIT TPGS */
3909	ff[i] = '\0';
3910	if (guid)
3911		ddi_devid_free_guid(guid);
3912
3913	/*
3914	 * Construct all applicable compatible forms. See comment at the
3915	 * head of the function for a description of the compatible forms.
3916	 */
3917	csp = compatp;
3918	p = (char *)(compatp + NCOMPAT);
3919
3920	/* ( 0) driver (optional, not documented in scsi(4)) */
3921	if (compat0) {
3922		*csp++ = p;
3923		(void) snprintf(p, tlen, "%s", compat0);
3924		len = strlen(p) + 1;
3925		p += len;
3926		tlen -= len;
3927	}
3928
3929	/* ( 1) scsiclass,DDEEFFF.vV.pP.rR */
3930	if ((dtype_device != dtype_node) && *gf && *vid && *pid && *rev) {
3931		*csp++ = p;
3932		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s.r%s",
3933		    dtype_node, dtype_device, gf, vid, pid, rev);
3934		len = strlen(p) + 1;
3935		p += len;
3936		tlen -= len;
3937	}
3938
3939	/* ( 2) scsiclass,DDEE.vV.pP.rR */
3940	if ((dtype_device != dtype_node) && *vid && *pid && *rev) {
3941		*csp++ = p;
3942		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s.r%s",
3943		    dtype_node, dtype_device, vid, pid, rev);
3944		len = strlen(p) + 1;
3945		p += len;
3946		tlen -= len;
3947	}
3948
3949	/* ( 3) scsiclass,DDFFF.vV.pP.rR */
3950	if (*gf && *vid && *pid && *rev) {
3951		*csp++ = p;
3952		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s.r%s",
3953		    dtype_node, gf, vid, pid, rev);
3954		len = strlen(p) + 1;
3955		p += len;
3956		tlen -= len;
3957	}
3958
3959	/* ( 4) scsiclass,DD.vV.pP.rR */
3960	if (*vid && *pid && *rev) {
3961		*csp++ = p;
3962		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s.r%s",
3963		    dtype_node, vid, pid, rev);
3964		len = strlen(p) + 1;
3965		p += len;
3966		tlen -= len;
3967	}
3968
3969	/* ( 5) scsiclass,DDEEFFF.vV.pP */
3970	if ((dtype_device != dtype_node) && *gf && *vid && *pid) {
3971		*csp++ = p;
3972		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s.v%s.p%s",
3973		    dtype_node, dtype_device, gf, vid, pid);
3974		len = strlen(p) + 1;
3975		p += len;
3976		tlen -= len;
3977	}
3978
3979	/* ( 6) scsiclass,DDEE.vV.pP */
3980	if ((dtype_device != dtype_node) && *vid && *pid) {
3981		*csp++ = p;
3982		(void) snprintf(p, tlen, "scsiclass,%02x%02x.v%s.p%s",
3983		    dtype_node, dtype_device, vid, pid);
3984		len = strlen(p) + 1;
3985		p += len;
3986		tlen -= len;
3987	}
3988
3989	/* ( 7) scsiclass,DDFFF.vV.pP */
3990	if (*gf && *vid && *pid) {
3991		*csp++ = p;
3992		(void) snprintf(p, tlen, "scsiclass,%02x%s.v%s.p%s",
3993		    dtype_node, gf, vid, pid);
3994		len = strlen(p) + 1;
3995		p += len;
3996		tlen -= len;
3997	}
3998
3999	/* ( 8) scsiclass,DD.vV.pP */
4000	if (*vid && *pid) {
4001		*csp++ = p;
4002		(void) snprintf(p, tlen, "scsiclass,%02x.v%s.p%s",
4003		    dtype_node, vid, pid);
4004		len = strlen(p) + 1;
4005		p += len;
4006		tlen -= len;
4007	}
4008
4009	/* (8.5) scsa,DD.bB (not documented in scsi(4)) */
4010	if (binding_set) {
4011		*csp++ = p;
4012		(void) snprintf(p, tlen, "scsa,%02x.b%s",
4013		    dtype_node, binding_set);
4014		len = strlen(p) + 1;
4015		p += len;
4016		tlen -= len;
4017	}
4018
4019	/* ( 9) scsiclass,DDEEFFF */
4020	if ((dtype_device != dtype_node) && *gf) {
4021		*csp++ = p;
4022		(void) snprintf(p, tlen, "scsiclass,%02x%02x%s",
4023		    dtype_node, dtype_device, gf);
4024		len = strlen(p) + 1;
4025		p += len;
4026		tlen -= len;
4027	}
4028
4029	/* (10) scsiclass,DDEE */
4030	if (dtype_device != dtype_node) {
4031		*csp++ = p;
4032		(void) snprintf(p, tlen, "scsiclass,%02x%02x",
4033		    dtype_node, dtype_device);
4034		len = strlen(p) + 1;
4035		p += len;
4036		tlen -= len;
4037	}
4038
4039	/* (11) scsiclass,DDFFF */
4040	if (*gf) {
4041		*csp++ = p;
4042		(void) snprintf(p, tlen, "scsiclass,%02x%s",
4043		    dtype_node, gf);
4044		len = strlen(p) + 1;
4045		p += len;
4046		tlen -= len;
4047	}
4048
4049	/* (12) scsiclass,DD */
4050	*csp++ = p;
4051	(void) snprintf(p, tlen, "scsiclass,%02x", dtype_node);
4052	len = strlen(p) + 1;
4053	p += len;
4054	tlen -= len;
4055
4056	/* (12.5) scsa.fFFF */
4057	if (*ff) {
4058		*csp++ = p;
4059		(void) snprintf(p, tlen, "scsa.f%s", ff);
4060		len = strlen(p) + 1;
4061		p += len;
4062		tlen -= len;
4063	}
4064
4065	/* (13) scsiclass */
4066	*csp++ = p;
4067	(void) snprintf(p, tlen, "scsiclass");
4068	len = strlen(p) + 1;
4069	p += len;
4070	tlen -= len;
4071	ASSERT(tlen >= 0);
4072
4073	*csp = NULL;			/* NULL terminate array of pointers */
4074	ncompat = csp - compatp;
4075
4076	/*
4077	 * When determining a nodename, a nodename_aliases specified
4078	 * mapping has precedence over using a driver_aliases specified
4079	 * driver binding as a nodename.
4080	 *
4081	 * See if any of the compatible forms have a nodename_aliases
4082	 * specified nodename. These mappings are described by
4083	 * nodename_aliases entries like:
4084	 *
4085	 *	disk		"scsiclass,00"
4086	 *	enclosure	"scsiclass,03.vSYMBIOS.pD1000"
4087	 *	ssd		"scsa,00.bfcp"
4088	 *
4089	 * All nodename_aliases mappings should idealy be to generic
4090	 * names, however a higher precedence legacy mapping to a
4091	 * driver name may exist. The highest precedence mapping
4092	 * provides the nodename, so legacy driver nodename mappings
4093	 * (if they exist) take precedence over generic nodename
4094	 * mappings.
4095	 */
4096	for (nname = NULL, csp = compatp; (nname == NULL) && *csp; csp++) {
4097		for (nap = na; nap->na_nodename; nap++) {
4098			if (strcmp(*csp, nap->na_alias) == 0) {
4099				nname = nap->na_nodename;
4100				break;
4101			}
4102		}
4103	}
4104
4105	/*
4106	 * Determine the driver name based on compatible (which may
4107	 * have the passed in compat0 as the first item). The driver_aliases
4108	 * file has entries like
4109	 *
4110	 *	sd	"scsiclass,00"
4111	 *
4112	 * that map compatible forms to specific drivers. These entries are
4113	 * established by add_drv/update_drv. We use the most specific
4114	 * driver binding as the nodename. This matches the eventual
4115	 * ddi_driver_compatible_major() binding that will be
4116	 * established by bind_node()
4117	 */
4118	for (dname = NULL, csp = compatp; *csp; csp++) {
4119		major = ddi_name_to_major(*csp);
4120		if ((major == DDI_MAJOR_T_NONE) ||
4121		    (devnamesp[major].dn_flags & DN_DRIVER_REMOVED))
4122			continue;
4123		if (dname = ddi_major_to_name(major))
4124			break;
4125	}
4126
4127	/*
4128	 * If no nodename_aliases mapping exists then use the
4129	 * driver_aliases specified driver binding as a nodename.
4130	 */
4131	if (nname == NULL)
4132		nname = dname;
4133
4134	/* return results */
4135	if (nname) {
4136		*nodenamep = kmem_alloc(strlen(nname) + 1, KM_SLEEP);
4137		(void) strcpy(*nodenamep, nname);
4138	} else {
4139		*nodenamep = NULL;
4140
4141		/*
4142		 * If no nodename could be determined return a special
4143		 * 'compatible' to be used for a diagnostic message. This
4144		 * compatible contains all compatible forms concatenated
4145		 * into a single string pointed to by the first element.
4146		 */
4147		for (csp = compatp; *(csp + 1); csp++)
4148			*((*csp) + strlen(*csp)) = ' ';
4149		*(compatp + 1) = NULL;
4150		ncompat = 1;
4151
4152	}
4153	if (drivernamep) {
4154		if (dname) {
4155			*drivernamep = kmem_alloc(strlen(dname) + 1, KM_SLEEP);
4156			(void) strcpy(*drivernamep, dname);
4157		} else
4158			*drivernamep = NULL;
4159	}
4160	*compatiblep = compatp;
4161	*ncompatiblep = ncompat;
4162}
4163
4164/*
4165 * Free allocations associated with scsi_hba_ident_nodename_compatible_get.
4166 */
4167static void
4168scsi_hba_ident_nodename_compatible_free(char *nodename, char *drivername,
4169    char **compatible)
4170{
4171	if (nodename)
4172		kmem_free(nodename, strlen(nodename) + 1);
4173	if (drivername)
4174		kmem_free(drivername, strlen(drivername) + 1);
4175	if (compatible)
4176		kmem_free(compatible, (NCOMPAT * sizeof (char *)) +
4177		    (NCOMPAT * COMPAT_LONGEST));
4178}
4179
4180void
4181scsi_hba_nodename_compatible_get(struct scsi_inquiry *inq,
4182    char *binding_set, int dtype_node, char *compat0,
4183    char **nodenamep, char ***compatiblep, int *ncompatiblep)
4184{
4185	scsi_hba_ident_nodename_compatible_get(inq,
4186	    NULL, 0, NULL, 0, binding_set, dtype_node, compat0, nodenamep,
4187	    NULL, compatiblep, ncompatiblep);
4188}
4189
4190void
4191scsi_hba_nodename_compatible_free(char *nodename, char **compatible)
4192{
4193	scsi_hba_ident_nodename_compatible_free(nodename, NULL, compatible);
4194}
4195
4196/* return the unit_address associated with a scsi_device */
4197char *
4198scsi_device_unit_address(struct scsi_device *sd)
4199{
4200	mdi_pathinfo_t	*pip;
4201
4202	ASSERT(sd && sd->sd_dev);
4203	if ((sd == NULL) || (sd->sd_dev == NULL))
4204		return (NULL);
4205
4206	pip = (mdi_pathinfo_t *)sd->sd_pathinfo;
4207	if (pip)
4208		return (mdi_pi_get_addr(pip));
4209	else
4210		return (ddi_get_name_addr(sd->sd_dev));
4211}
4212
4213/* scsi_device property interfaces */
4214#define	_TYPE_DEFINED(flags)						\
4215	(((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_PATH) || \
4216	((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_DEVICE))
4217
4218#define	_DEVICE_PIP(sd, flags)						\
4219	((((flags & SCSI_DEVICE_PROP_TYPE_MSK) == SCSI_DEVICE_PROP_PATH) && \
4220	sd->sd_pathinfo) ? (mdi_pathinfo_t *)sd->sd_pathinfo : NULL)
4221
4222int
4223scsi_device_prop_get_int(struct scsi_device *sd, uint_t flags,
4224    char *name, int defval)
4225{
4226	mdi_pathinfo_t	*pip;
4227	int		v = defval;
4228	int		data;
4229	int		rv;
4230
4231	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4232	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4233	    !_TYPE_DEFINED(flags))
4234		return (v);
4235
4236	pip = _DEVICE_PIP(sd, flags);
4237	if (pip) {
4238		rv = mdi_prop_lookup_int(pip, name, &data);
4239		if (rv == DDI_PROP_SUCCESS)
4240			v = data;
4241	} else
4242		v = ddi_prop_get_int(DDI_DEV_T_ANY, sd->sd_dev,
4243		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4244	return (v);
4245}
4246
4247
4248int64_t
4249scsi_device_prop_get_int64(struct scsi_device *sd, uint_t flags,
4250    char *name, int64_t defval)
4251{
4252	mdi_pathinfo_t	*pip;
4253	int64_t		v = defval;
4254	int64_t		data;
4255	int		rv;
4256
4257	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4258	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4259	    !_TYPE_DEFINED(flags))
4260		return (v);
4261
4262	pip = _DEVICE_PIP(sd, flags);
4263	if (pip) {
4264		rv = mdi_prop_lookup_int64(pip, name, &data);
4265		if (rv == DDI_PROP_SUCCESS)
4266			v = data;
4267	} else
4268		v = ddi_prop_get_int64(DDI_DEV_T_ANY, sd->sd_dev,
4269		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4270	return (v);
4271}
4272
4273int
4274scsi_device_prop_lookup_byte_array(struct scsi_device *sd, uint_t flags,
4275    char *name, uchar_t **data, uint_t *nelements)
4276{
4277	mdi_pathinfo_t	*pip;
4278	int		rv;
4279
4280	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4281	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4282	    !_TYPE_DEFINED(flags))
4283		return (DDI_PROP_INVAL_ARG);
4284
4285	pip = _DEVICE_PIP(sd, flags);
4286	if (pip)
4287		rv = mdi_prop_lookup_byte_array(pip, name, data, nelements);
4288	else
4289		rv = ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, sd->sd_dev,
4290		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4291		    name, data, nelements);
4292	return (rv);
4293}
4294
4295int
4296scsi_device_prop_lookup_int_array(struct scsi_device *sd, uint_t flags,
4297    char *name, int **data, uint_t *nelements)
4298{
4299	mdi_pathinfo_t	*pip;
4300	int		rv;
4301
4302	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4303	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4304	    !_TYPE_DEFINED(flags))
4305		return (DDI_PROP_INVAL_ARG);
4306
4307	pip = _DEVICE_PIP(sd, flags);
4308	if (pip)
4309		rv = mdi_prop_lookup_int_array(pip, name, data, nelements);
4310	else
4311		rv = ddi_prop_lookup_int_array(DDI_DEV_T_ANY, sd->sd_dev,
4312		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4313		    name, data, nelements);
4314	return (rv);
4315}
4316
4317
4318int
4319scsi_device_prop_lookup_string(struct scsi_device *sd, uint_t flags,
4320    char *name, char **data)
4321{
4322	mdi_pathinfo_t	*pip;
4323	int		rv;
4324
4325	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4326	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4327	    !_TYPE_DEFINED(flags))
4328		return (DDI_PROP_INVAL_ARG);
4329
4330	pip = _DEVICE_PIP(sd, flags);
4331	if (pip)
4332		rv = mdi_prop_lookup_string(pip, name, data);
4333	else
4334		rv = ddi_prop_lookup_string(DDI_DEV_T_ANY, sd->sd_dev,
4335		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4336		    name, data);
4337	return (rv);
4338}
4339
4340int
4341scsi_device_prop_lookup_string_array(struct scsi_device *sd, uint_t flags,
4342    char *name, char ***data, uint_t *nelements)
4343{
4344	mdi_pathinfo_t	*pip;
4345	int		rv;
4346
4347	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4348	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4349	    !_TYPE_DEFINED(flags))
4350		return (DDI_PROP_INVAL_ARG);
4351
4352	pip = _DEVICE_PIP(sd, flags);
4353	if (pip)
4354		rv = mdi_prop_lookup_string_array(pip, name, data, nelements);
4355	else
4356		rv = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, sd->sd_dev,
4357		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4358		    name, data, nelements);
4359	return (rv);
4360}
4361
4362int
4363scsi_device_prop_update_byte_array(struct scsi_device *sd, uint_t flags,
4364    char *name, uchar_t *data, uint_t nelements)
4365{
4366	mdi_pathinfo_t	*pip;
4367	int		rv;
4368
4369	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4370	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4371	    !_TYPE_DEFINED(flags))
4372		return (DDI_PROP_INVAL_ARG);
4373
4374	pip = _DEVICE_PIP(sd, flags);
4375	if (pip)
4376		rv = mdi_prop_update_byte_array(pip, name, data, nelements);
4377	else
4378		rv = ndi_prop_update_byte_array(DDI_DEV_T_NONE, sd->sd_dev,
4379		    name, data, nelements);
4380	return (rv);
4381}
4382
4383int
4384scsi_device_prop_update_int(struct scsi_device *sd, uint_t flags,
4385    char *name, int data)
4386{
4387	mdi_pathinfo_t	*pip;
4388	int		rv;
4389
4390	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4391	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4392	    !_TYPE_DEFINED(flags))
4393		return (DDI_PROP_INVAL_ARG);
4394
4395	pip = _DEVICE_PIP(sd, flags);
4396	if (pip)
4397		rv = mdi_prop_update_int(pip, name, data);
4398	else
4399		rv = ndi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
4400		    name, data);
4401	return (rv);
4402}
4403
4404int
4405scsi_device_prop_update_int64(struct scsi_device *sd, uint_t flags,
4406    char *name, int64_t data)
4407{
4408	mdi_pathinfo_t	*pip;
4409	int		rv;
4410
4411	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4412	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4413	    !_TYPE_DEFINED(flags))
4414		return (DDI_PROP_INVAL_ARG);
4415
4416	pip = _DEVICE_PIP(sd, flags);
4417	if (pip)
4418		rv = mdi_prop_update_int64(pip, name, data);
4419	else
4420		rv = ndi_prop_update_int64(DDI_DEV_T_NONE, sd->sd_dev,
4421		    name, data);
4422	return (rv);
4423}
4424
4425int
4426scsi_device_prop_update_int_array(struct scsi_device *sd, uint_t flags,
4427    char *name, int *data, uint_t nelements)
4428{
4429	mdi_pathinfo_t	*pip;
4430	int		rv;
4431
4432	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4433	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4434	    !_TYPE_DEFINED(flags))
4435		return (DDI_PROP_INVAL_ARG);
4436
4437	pip = _DEVICE_PIP(sd, flags);
4438	if (pip)
4439		rv = mdi_prop_update_int_array(pip, name, data, nelements);
4440	else
4441		rv = ndi_prop_update_int_array(DDI_DEV_T_NONE, sd->sd_dev,
4442		    name, data, nelements);
4443	return (rv);
4444}
4445
4446int
4447scsi_device_prop_update_string(struct scsi_device *sd, uint_t flags,
4448    char *name, char *data)
4449{
4450	mdi_pathinfo_t	*pip;
4451	int		rv;
4452
4453	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4454	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4455	    !_TYPE_DEFINED(flags))
4456		return (DDI_PROP_INVAL_ARG);
4457
4458	pip = _DEVICE_PIP(sd, flags);
4459	if (pip)
4460		rv = mdi_prop_update_string(pip, name, data);
4461	else
4462		rv = ndi_prop_update_string(DDI_DEV_T_NONE, sd->sd_dev,
4463		    name, data);
4464	return (rv);
4465}
4466
4467int
4468scsi_device_prop_update_string_array(struct scsi_device *sd, uint_t flags,
4469    char *name, char **data, uint_t nelements)
4470{
4471	mdi_pathinfo_t	*pip;
4472	int		rv;
4473
4474	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4475	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4476	    !_TYPE_DEFINED(flags))
4477		return (DDI_PROP_INVAL_ARG);
4478
4479	pip = _DEVICE_PIP(sd, flags);
4480	if (pip)
4481		rv = mdi_prop_update_string_array(pip, name, data, nelements);
4482	else
4483		rv = ndi_prop_update_string_array(DDI_DEV_T_NONE, sd->sd_dev,
4484		    name, data, nelements);
4485	return (rv);
4486}
4487
4488int
4489scsi_device_prop_remove(struct scsi_device *sd, uint_t flags, char *name)
4490{
4491	mdi_pathinfo_t	*pip;
4492	int		rv;
4493
4494	ASSERT(sd && name && sd->sd_dev && _TYPE_DEFINED(flags));
4495	if ((sd == NULL) || (name == NULL) || (sd->sd_dev == NULL) ||
4496	    !_TYPE_DEFINED(flags))
4497		return (DDI_PROP_INVAL_ARG);
4498
4499	pip = _DEVICE_PIP(sd, flags);
4500	if (pip)
4501		rv = mdi_prop_remove(pip, name);
4502	else
4503		rv = ndi_prop_remove(DDI_DEV_T_NONE, sd->sd_dev, name);
4504	return (rv);
4505}
4506
4507void
4508scsi_device_prop_free(struct scsi_device *sd, uint_t flags, void *data)
4509{
4510	mdi_pathinfo_t	*pip;
4511
4512	ASSERT(sd && data && sd->sd_dev && _TYPE_DEFINED(flags));
4513	if ((sd == NULL) || (data == NULL) || (sd->sd_dev == NULL) ||
4514	    !_TYPE_DEFINED(flags))
4515		return;
4516
4517	pip = _DEVICE_PIP(sd, flags);
4518	if (pip)
4519		(void) mdi_prop_free(data);
4520	else
4521		ddi_prop_free(data);
4522}
4523
4524/* SMP device property interfaces */
4525int
4526smp_device_prop_get_int(struct smp_device *smp_sd, char *name, int defval)
4527{
4528	int		v = defval;
4529
4530	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4531	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4532		return (v);
4533
4534	v = ddi_prop_get_int(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4535	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4536	return (v);
4537}
4538
4539
4540int64_t
4541smp_device_prop_get_int64(struct smp_device *smp_sd, char *name, int64_t defval)
4542{
4543	int64_t		v = defval;
4544
4545	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4546	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4547		return (v);
4548
4549	v = ddi_prop_get_int64(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4550	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, name, v);
4551	return (v);
4552}
4553
4554int
4555smp_device_prop_lookup_byte_array(struct smp_device *smp_sd, char *name,
4556    uchar_t **data, uint_t *nelements)
4557{
4558	int		rv;
4559
4560	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4561	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4562		return (DDI_PROP_INVAL_ARG);
4563
4564	rv = ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4565	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4566	    name, data, nelements);
4567	return (rv);
4568}
4569
4570int
4571smp_device_prop_lookup_int_array(struct smp_device *smp_sd, char *name,
4572    int **data, uint_t *nelements)
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_int_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4581	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4582	    name, data, nelements);
4583	return (rv);
4584}
4585
4586
4587int
4588smp_device_prop_lookup_string(struct smp_device *smp_sd, char *name,
4589    char **data)
4590{
4591	int		rv;
4592
4593	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4594	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4595		return (DDI_PROP_INVAL_ARG);
4596
4597	rv = ddi_prop_lookup_string(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4598	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4599	    name, data);
4600	return (rv);
4601}
4602
4603int
4604smp_device_prop_lookup_string_array(struct smp_device *smp_sd, char *name,
4605    char ***data, uint_t *nelements)
4606{
4607	int		rv;
4608
4609	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4610	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4611		return (DDI_PROP_INVAL_ARG);
4612
4613	rv = ddi_prop_lookup_string_array(DDI_DEV_T_ANY, smp_sd->smp_sd_dev,
4614	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
4615	    name, data, nelements);
4616	return (rv);
4617}
4618
4619int
4620smp_device_prop_update_byte_array(struct smp_device *smp_sd, char *name,
4621    uchar_t *data, uint_t nelements)
4622{
4623	int		rv;
4624
4625	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4626	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4627		return (DDI_PROP_INVAL_ARG);
4628
4629	rv = ndi_prop_update_byte_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4630	    name, data, nelements);
4631	return (rv);
4632}
4633
4634int
4635smp_device_prop_update_int(struct smp_device *smp_sd, char *name, int data)
4636{
4637	int		rv;
4638
4639	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4640	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4641		return (DDI_PROP_INVAL_ARG);
4642
4643	rv = ndi_prop_update_int(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4644	    name, data);
4645	return (rv);
4646}
4647
4648int
4649smp_device_prop_update_int64(struct smp_device *smp_sd, char *name,
4650    int64_t data)
4651{
4652	int		rv;
4653
4654	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4655	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4656		return (DDI_PROP_INVAL_ARG);
4657
4658	rv = ndi_prop_update_int64(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4659	    name, data);
4660	return (rv);
4661}
4662
4663int
4664smp_device_prop_update_int_array(struct smp_device *smp_sd, char *name,
4665    int *data, uint_t nelements)
4666{
4667	int		rv;
4668
4669	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4670	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4671		return (DDI_PROP_INVAL_ARG);
4672
4673	rv = ndi_prop_update_int_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4674	    name, data, nelements);
4675	return (rv);
4676}
4677
4678int
4679smp_device_prop_update_string(struct smp_device *smp_sd, char *name, char *data)
4680{
4681	int		rv;
4682
4683	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4684	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4685		return (DDI_PROP_INVAL_ARG);
4686
4687	rv = ndi_prop_update_string(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4688	    name, data);
4689	return (rv);
4690}
4691
4692int
4693smp_device_prop_update_string_array(struct smp_device *smp_sd, char *name,
4694    char **data, uint_t nelements)
4695{
4696	int		rv;
4697
4698	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4699	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4700		return (DDI_PROP_INVAL_ARG);
4701
4702	rv = ndi_prop_update_string_array(DDI_DEV_T_NONE, smp_sd->smp_sd_dev,
4703	    name, data, nelements);
4704	return (rv);
4705}
4706
4707int
4708smp_device_prop_remove(struct smp_device *smp_sd, char *name)
4709{
4710	int		rv;
4711
4712	ASSERT(smp_sd && name && smp_sd->smp_sd_dev);
4713	if ((smp_sd == NULL) || (name == NULL) || (smp_sd->smp_sd_dev == NULL))
4714		return (DDI_PROP_INVAL_ARG);
4715
4716	rv = ndi_prop_remove(DDI_DEV_T_NONE, smp_sd->smp_sd_dev, name);
4717	return (rv);
4718}
4719
4720void
4721smp_device_prop_free(struct smp_device *smp_sd, void *data)
4722{
4723	ASSERT(smp_sd && data && smp_sd->smp_sd_dev);
4724	if ((smp_sd == NULL) || (data == NULL) || (smp_sd->smp_sd_dev == NULL))
4725		return;
4726
4727	ddi_prop_free(data);
4728}
4729
4730/*
4731 * scsi_hba_ua_set: given "unit-address" string, set properties.
4732 *
4733 * Function to set the properties on a devinfo or pathinfo node from
4734 * the "unit-address" part of a "name@unit-address" /devices path 'name'
4735 * string.
4736 *
4737 * This function works in conjunction with scsi_ua_get()/scsi_hba_ua_get()
4738 * (and possibly with an HBA driver's tran_tgt_init() implementation).
4739 */
4740static int
4741scsi_hba_ua_set(char *ua, dev_info_t *dchild, mdi_pathinfo_t *pchild)
4742{
4743	char		*p;
4744	int		tgt;
4745	char		*tgt_port_end;
4746	char		*tgt_port;
4747	int		tgt_port_len;
4748	int		sfunc;
4749	scsi_lun64_t	lun64;
4750
4751	/* Caller must choose to decorate devinfo *or* pathinfo */
4752	ASSERT((dchild != NULL) ^ (pchild != NULL));
4753	if (dchild && pchild)
4754		return (0);
4755
4756	/*
4757	 * generic implementation based on "tgt,lun[,sfunc]" address form.
4758	 * parse hex "tgt" part of "tgt,lun[,sfunc]"
4759	 */
4760	p = ua;
4761	tgt_port_end = NULL;
4762	for (tgt = 0; *p && *p != ','; p++) {
4763		if (*p >= '0' && *p <= '9')
4764			tgt = (tgt << 4) + (*p - '0');
4765		else if (*p >= 'a' && *p <= 'f')
4766			tgt = (tgt << 4) + 10 + (*p - 'a');
4767		else
4768			tgt = -1;		/* non-numeric */
4769
4770		/*
4771		 * if non-numeric or our of range set tgt to -1 and
4772		 * skip forward
4773		 */
4774		if (tgt < 0) {
4775			tgt = -1;
4776			for (; *p && *p != ','; p++)
4777				;
4778			break;
4779		}
4780	}
4781	tgt_port_end = p;
4782
4783	/* parse hex ",lun" part of "tgt,lun[,sfunc]" */
4784	if (*p)
4785		p++;
4786	for (lun64 = 0; *p && *p != ','; p++) {
4787		if (*p >= '0' && *p <= '9')
4788			lun64 = (lun64 << 4) + (*p - '0');
4789		else if (*p >= 'a' && *p <= 'f')
4790			lun64 = (lun64 << 4) + 10 + (*p - 'a');
4791		else
4792			return (0);
4793	}
4794
4795	/* parse hex ",sfunc" part of "tgt,lun[,sfunc]" */
4796	if (*p) {
4797		p++;
4798		for (sfunc = 0; *p; p++) {
4799			if (*p >= '0' && *p <= '9')
4800				sfunc = (sfunc << 4) + (*p - '0');
4801			else if (*p >= 'a' && *p <= 'f')
4802				sfunc = (sfunc << 4) + 10 + (*p - 'a');
4803			else
4804				return (0);
4805		}
4806	} else
4807		sfunc = -1;
4808
4809	if (dchild) {
4810		/*
4811		 * Decorate a devinfo node with unit address properties.
4812		 * This adds the the addressing properties needed to
4813		 * DDI_CTLOPS_UNINITCHILD the devinfo node (i.e. perform
4814		 * the reverse operation - form unit address from properties).
4815		 */
4816		if ((tgt != -1) && (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4817		    SCSI_ADDR_PROP_TARGET, tgt) != DDI_PROP_SUCCESS))
4818			return (0);
4819
4820		if (tgt_port_end) {
4821			tgt_port_len = tgt_port_end - ua + 1;
4822			tgt_port = kmem_alloc(tgt_port_len, KM_SLEEP);
4823			(void) strlcpy(tgt_port, ua, tgt_port_len);
4824			if (ndi_prop_update_string(DDI_DEV_T_NONE, dchild,
4825			    SCSI_ADDR_PROP_TARGET_PORT, tgt_port) !=
4826			    DDI_PROP_SUCCESS) {
4827				kmem_free(tgt_port, tgt_port_len);
4828				return (0);
4829			}
4830			kmem_free(tgt_port, tgt_port_len);
4831		}
4832
4833		/* Set the appropriate lun properties. */
4834		if (lun64 < SCSI_32LUNS_PER_TARGET) {
4835			if (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4836			    SCSI_ADDR_PROP_LUN, (int)lun64) != DDI_PROP_SUCCESS)
4837				return (0);
4838		}
4839		if (ndi_prop_update_int64(DDI_DEV_T_NONE, dchild,
4840		    SCSI_ADDR_PROP_LUN64, lun64) != DDI_PROP_SUCCESS)
4841			return (0);
4842
4843		/* Set the sfunc property */
4844		if ((sfunc != -1) &&
4845		    (ndi_prop_update_int(DDI_DEV_T_NONE, dchild,
4846		    SCSI_ADDR_PROP_SFUNC, (int)sfunc) != DDI_PROP_SUCCESS))
4847			return (0);
4848	} else if (pchild) {
4849		/*
4850		 * Decorate a pathinfo node with unit address properties.
4851		 */
4852		if ((tgt != -1) && (mdi_prop_update_int(pchild,
4853		    SCSI_ADDR_PROP_TARGET, tgt) != DDI_PROP_SUCCESS))
4854			return (0);
4855
4856		if (tgt_port_end) {
4857			tgt_port_len = tgt_port_end - ua + 1;
4858			tgt_port = kmem_alloc(tgt_port_len, KM_SLEEP);
4859			(void) strlcpy(tgt_port, ua, tgt_port_len);
4860			if (mdi_prop_update_string(pchild,
4861			    SCSI_ADDR_PROP_TARGET_PORT, tgt_port) !=
4862			    DDI_PROP_SUCCESS) {
4863				kmem_free(tgt_port, tgt_port_len);
4864				return (0);
4865			}
4866			kmem_free(tgt_port, tgt_port_len);
4867		}
4868
4869		/* Set the appropriate lun properties */
4870		if (lun64 < SCSI_32LUNS_PER_TARGET) {
4871			if (mdi_prop_update_int(pchild, SCSI_ADDR_PROP_LUN,
4872			    (int)lun64) != DDI_PROP_SUCCESS)
4873				return (0);
4874		}
4875
4876		if (mdi_prop_update_int64(pchild, SCSI_ADDR_PROP_LUN64,
4877		    lun64) != DDI_PROP_SUCCESS)
4878			return (0);
4879
4880		/* Set the sfunc property */
4881		if ((sfunc != -1) &&
4882		    (mdi_prop_update_int(pchild,
4883		    SCSI_ADDR_PROP_SFUNC, (int)sfunc) != DDI_PROP_SUCCESS))
4884			return (0);
4885	}
4886	return (1);
4887}
4888
4889/*
4890 * Private ndi_devi_find/mdi_pi_find implementation - find the child
4891 * dev_info/path_info of self whose phci name matches "name@caddr".
4892 * We have our own implementation because we need to search with both
4893 * forms of sibling lists (dev_info and path_info) and we need to be able
4894 * to search with a NULL name in order to find siblings already associated
4895 * with a given unit-address (same @addr). NOTE: NULL name search will never
4896 * return probe node.
4897 *
4898 * If pchildp is NULL and we find a pathinfo child, we return the client
4899 * devinfo node in *dchildp.
4900 *
4901 * The init flag argument should be clear when called from places where
4902 * recursion could occur (like scsi_busctl_initchild) and when the caller
4903 * has already performed a search for name@addr with init set (performance).
4904 *
4905 * Future: Integrate ndi_devi_findchild_by_callback into scsi_findchild.
4906 */
4907static int
4908scsi_findchild(dev_info_t *self, char *name, char *addr, int init,
4909    dev_info_t **dchildp, mdi_pathinfo_t **pchildp, int *ppi)
4910{
4911	dev_info_t	*dchild;	/* devinfo child */
4912	mdi_pathinfo_t	*pchild;	/* pathinfo child */
4913	int		found = CHILD_TYPE_NONE;
4914	char		*daddr;
4915
4916	ASSERT(self && DEVI_BUSY_OWNED(self));
4917	ASSERT(addr && dchildp);
4918	if ((self == NULL) || (addr == NULL) || (dchildp == NULL))
4919		return (CHILD_TYPE_NONE);
4920
4921	*dchildp = NULL;
4922	if (pchildp)
4923		*pchildp = NULL;
4924	if (ppi)
4925		*ppi = 0;
4926
4927	/* Walk devinfo child list to find a match */
4928	for (dchild = ddi_get_child(self); dchild;
4929	    dchild = ddi_get_next_sibling(dchild)) {
4930		if (i_ddi_node_state(dchild) < DS_INITIALIZED)
4931			continue;
4932
4933		daddr = ddi_get_name_addr(dchild);
4934		if (daddr && (strcmp(addr, daddr) == 0) &&
4935		    ((name == NULL) ||
4936		    (strcmp(name, DEVI(dchild)->devi_node_name) == 0))) {
4937			/*
4938			 * If we are asked to find "anything" at a given
4939			 * unit-address (name == NULL), we don't realy want
4940			 * to find the 'probe' node. The existance of
4941			 * a probe node on a 'name == NULL' search should
4942			 * fail.  This will trigger slow-path code where
4943			 * we explicity look for, and synchronize against,
4944			 * a node named "probe" at the unit-address.
4945			 */
4946			if ((name == NULL) &&
4947			    scsi_hba_devi_is_barrier(dchild)) {
4948				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4949				    "%s@%s 'probe' devinfo found, skip",
4950				    name ? name : "", addr));
4951				continue;
4952			}
4953
4954			/* We have found a match. */
4955			found |= CHILD_TYPE_DEVINFO;
4956			SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4957			    "%s@%s devinfo found", name ? name : "", addr));
4958			*dchildp = dchild;		/* devinfo found */
4959			break;
4960		}
4961	}
4962
4963	/*
4964	 * Walk pathinfo child list to find a match.
4965	 *
4966	 * NOTE: Unlike devinfo nodes, pathinfo nodes have a string searchable
4967	 * unit-address from creation - so there is no need for an 'init'
4968	 * search block of code for pathinfo nodes below.
4969	 */
4970	pchild = mdi_pi_find(self, NULL, addr);
4971	if (pchild) {
4972		/*
4973		 * NOTE: If name specified and we match a pathinfo unit
4974		 * address, we don't check the client node name.
4975		 */
4976		if (ppi)
4977			*ppi = mdi_pi_get_path_instance(pchild);
4978		found |= CHILD_TYPE_PATHINFO;
4979
4980		if (pchildp) {
4981			SCSI_HBA_LOG((_LOG(4), self, NULL,
4982			    "%s pathinfo found", mdi_pi_spathname(pchild)));
4983			*pchildp = pchild;		/* pathinfo found */
4984		} else if (*dchildp == NULL) {
4985			/*
4986			 * Did not find a devinfo node, found a pathinfo node,
4987			 * but caller did not ask us to return a pathinfo node:
4988			 * we return the 'client' devinfo node instead (but
4989			 * with CHILD_TYPE_PATHINFO 'found' return value).
4990			 */
4991			dchild = mdi_pi_get_client(pchild);
4992			SCSI_HBA_LOG((_LOG(4), NULL, dchild,
4993			    "%s pathinfo found, client switch",
4994			    mdi_pi_spathname(pchild)));
4995
4996			/*
4997			 * A pathinfo node always has a 'client' devinfo node,
4998			 * but we need to ensure that the 'client' is
4999			 * initialized and has a scsi_device structure too.
5000			 */
5001			ASSERT(dchild);
5002			if (i_ddi_node_state(dchild) < DS_INITIALIZED) {
5003				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5004				    "%s found client, initchild",
5005				    mdi_pi_spathname(pchild)));
5006				(void) ddi_initchild(ddi_get_parent(dchild),
5007				    dchild);
5008			}
5009			if (i_ddi_node_state(dchild) >= DS_INITIALIZED) {
5010				/* client found and initialized */
5011				*dchildp = dchild;
5012			} else {
5013				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5014				    "%s found client, but failed initchild",
5015				    mdi_pi_spathname(pchild)));
5016			}
5017		}
5018	}
5019
5020	/* Try devinfo again with initchild of uninitialized nodes */
5021	if ((found == CHILD_TYPE_NONE) && init) {
5022		for (dchild = ddi_get_child(self); dchild;
5023		    dchild = ddi_get_next_sibling(dchild)) {
5024			/* skip if checked above */
5025			if (i_ddi_node_state(dchild) >= DS_INITIALIZED)
5026				continue;
5027			/* attempt initchild to establish unit-address */
5028			(void) ddi_initchild(self, dchild);
5029			if (i_ddi_node_state(dchild) < DS_INITIALIZED)
5030				continue;
5031			daddr = ddi_get_name_addr(dchild);
5032			if (daddr &&
5033			    ((name == NULL) || (strcmp(name,
5034			    DEVI(dchild)->devi_node_name) == 0)) &&
5035			    (strcmp(addr, daddr) == 0)) {
5036				found |= CHILD_TYPE_DEVINFO;
5037				SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5038				    "%s@%s devinfo found post initchild",
5039				    name ? name : "", addr));
5040				*dchildp = dchild;	/* devinfo found */
5041				break;	/* node found */
5042			}
5043		}
5044	}
5045
5046	/*
5047	 * We should never find devinfo and pathinfo at the same
5048	 * unit-address.
5049	 */
5050	ASSERT(found != (CHILD_TYPE_DEVINFO | CHILD_TYPE_PATHINFO));
5051	if (found == (CHILD_TYPE_DEVINFO | CHILD_TYPE_PATHINFO)) {
5052		found = CHILD_TYPE_NONE;
5053		*dchildp = NULL;
5054		*pchildp = NULL;
5055	}
5056	return (found);
5057}
5058
5059/*
5060 * Given information about a child device (contained on probe node) construct
5061 * and return a pointer to the dynamic SID devinfo node associated with the
5062 * device. In the creation of this SID node a compatible property for the
5063 * device is formed and used to establish a nodename (via
5064 * /etc/nodename_aliases) and to bind a driver (via /etc/driver_aliases).
5065 *
5066 * If this routine is called then we got a response from a device and
5067 * obtained the inquiry data from the device. Some inquiry results indicate
5068 * that the specific LUN we addressed does not exist, and we don't want to
5069 * bind a standard target driver to the node we create. Even though the
5070 * specific LUN is not usable, the framework may still want to bind a
5071 * target driver to the device for internal communication with the device -
5072 * an example would be issuing a report_lun to enumerate other LUNs under a
5073 * DPQ_NEVER LUN0. Another example would be wanting to known that the
5074 * DPQ_NEVER LUN0 device exists in BUS_CONFIG_ONE for non-existent LUN
5075 * caching optimizations. To support this we let the caller specify a
5076 * compatible property (or driver). If LUN0 inquiry data indicates that the
5077 * LUN does not exist then we establish compat0 as the highest precedence(0)
5078 * compatible form. If used, this compat0 driver will never be called on to
5079 * issue external commands to the device.
5080 *
5081 * If no driver binds to the device using driver_alias we establish the driver
5082 * passed in as the node name.
5083 */
5084
5085extern int e_devid_cache_pathinfo(mdi_pathinfo_t *, ddi_devid_t);
5086
5087static int
5088scsi_device_createchild(dev_info_t *self, char *addr, scsi_enum_t se,
5089    struct scsi_device *sdprobe, dev_info_t **dchildp, mdi_pathinfo_t **pchildp)
5090{
5091	scsi_lun64_t		lun64;
5092	int			dtype;
5093	int			dpq;
5094	int			dpq_vu;
5095	int			dtype_node;
5096	int			lunexists;
5097	char			*compat0;
5098	char			*nname;
5099	char			**compat = NULL;
5100	int			ncompat;
5101	dev_info_t		*dchild = NULL;
5102	mdi_pathinfo_t		*pchild = NULL;
5103	dev_info_t		*probe = sdprobe->sd_dev;
5104	struct scsi_inquiry	*inq = sdprobe->sd_inq;
5105	uchar_t			*inq80 = NULL;
5106	uchar_t			*inq83 = NULL;
5107	uint_t			inq80len, inq83len;
5108	char			*binding_set = NULL;
5109	char			*dname = NULL;
5110	ddi_devid_t		devid;
5111	int			have_devid = 0;
5112	ddi_devid_t		cdevid;
5113	int			have_cdevid = 0;
5114	char			*devid_str;
5115	char			*guid = NULL;
5116
5117	ASSERT(self && addr && *addr && DEVI_BUSY_OWNED(self));
5118	ASSERT(dchildp && pchildp);
5119
5120	/*
5121	 * Determine the lun and whether the lun exists. We may need to create
5122	 * a node for LUN0 (with compat0 driver binding) even if the lun does
5123	 * not exist - so we can run report_lun to find additional LUNs.
5124	 */
5125	lun64 = scsi_addr_to_lun64(addr);
5126	dtype = inq->inq_dtype & DTYPE_MASK;		/* device */
5127	dpq = inq->inq_dtype & DPQ_MASK;
5128	dpq_vu = inq->inq_dtype & DPQ_VUNIQ ? 1 : 0;
5129
5130	dtype_node = scsi_addr_to_sfunc(addr);		/* secondary function */
5131	if (dtype_node == -1)
5132		dtype_node = dtype;			/* node for device */
5133
5134	lunexists = (dtype != dtype_node) ||		/* override */
5135	    ((dpq_vu == 0) && (dpq == DPQ_POSSIBLE)) ||	/* ANSII */
5136	    (dpq_vu && (lun64 == 0));			/* VU LUN0 */
5137	if (dtype == DTYPE_UNKNOWN)
5138		lunexists = 0;
5139
5140	SCSI_HBA_LOG((_LOG(4), self, NULL,
5141	    "@%s dtype %x %x dpq_vu %d dpq %x: %d",
5142	    addr, dtype, dtype_node, dpq_vu, dpq, lunexists));
5143
5144	/* A non-existent LUN0 uses compatible_nodev. */
5145	if (lunexists) {
5146		compat0 = NULL;				/* compat0 not needed */
5147	} else if (lun64 == 0) {
5148		compat0 = compatible_nodev;
5149		SCSI_HBA_LOG((_LOG(2), self, NULL,
5150		    "@%s lun 0 with compat0 %s", addr, compat0));
5151	} else
5152		goto out;				/* no node created */
5153
5154	/* Obtain identity information from probe node. */
5155	if (ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, probe,
5156	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "inquiry-page-80",
5157	    &inq80, &inq80len) != DDI_PROP_SUCCESS)
5158		inq80 = NULL;
5159	if (ddi_prop_lookup_byte_array(DDI_DEV_T_ANY, probe,
5160	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "inquiry-page-83",
5161	    &inq83, &inq83len) != DDI_PROP_SUCCESS)
5162		inq83 = NULL;
5163
5164	/* Get "scsi-binding-set" property (if there is one). */
5165	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, self,
5166	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM,
5167	    "scsi-binding-set", &binding_set) == DDI_PROP_SUCCESS)
5168		SCSI_HBA_LOG((_LOG(2), NULL, probe,
5169		    "binding_set '%s'", binding_set));
5170
5171	/* determine the node name and compatible information */
5172	scsi_hba_ident_nodename_compatible_get(inq,
5173	    inq80, inq80len, inq83, inq83len, binding_set, dtype_node,
5174	    compat0, &nname, &dname, &compat, &ncompat);
5175
5176	if (nname == NULL) {
5177		/*
5178		 * We will not be able to create a node because we could not
5179		 * determine a node name. Print out a NODRIVER level warning
5180		 * message with the compatible forms for the device. Note that
5181		 * there may be a driver.conf node that attaches to the device,
5182		 * which is why we only produce this warning message for debug
5183		 * kernels.
5184		 */
5185		SCSI_HBA_LOG((_LOG(1), NULL, self,
5186		    "no node_name for device @%s:\n	 compatible: %s",
5187		    addr, *compat));
5188		goto out;
5189	}
5190
5191	/*
5192	 * FUTURE: some day we may want an accurate "compatible" on the probe
5193	 * node so that vhci_is_dev_supported() in scsi_vhci could, at
5194	 * least in part, determine/configure based on "compatible".
5195	 *
5196	 *	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, probe,
5197	 *	    "compatible", compat, ncompat) != DDI_PROP_SUCCESS) {
5198	 *		SCSI_HBA_LOG((_LOG(3), self, NULL,
5199	 *		    "%s@%s failed probe compatible decoration",
5200	 *		    nname, addr));
5201	 *		goto out;
5202	 *	}
5203	 */
5204
5205	/* Encode devid from identity information. */
5206	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST, dname,
5207	    (uchar_t *)inq, sizeof (*inq), inq80, inq80len, inq83, inq83len,
5208	    &devid) == DDI_SUCCESS) {
5209		have_devid = 1;
5210
5211		/* Attempt to form guid from devid. */
5212		guid = ddi_devid_to_guid(devid);
5213
5214		/* Produce string devid for debug. */
5215		devid_str = ddi_devid_str_encode(devid, NULL);
5216		SCSI_HBA_LOG((_LOG(3), self, probe, "devid '%s' guid '%s'",
5217		    devid_str ? devid_str : "NULL", guid ? guid : "NULL"));
5218		ddi_devid_str_free(devid_str);
5219	}
5220
5221
5222	/*
5223	 * Determine if the device should be enumerated as under the vHCI
5224	 * (client node) or under the pHCI. By convention scsi_vhci expects
5225	 * the "cinfo" argument identity information to be represented as a
5226	 * devinfo node with the needed information (i.e. the pHCI probe node).
5227	 */
5228	if ((guid == NULL) ||
5229	    (mdi_is_dev_supported(MDI_HCI_CLASS_SCSI, self, sdprobe) !=
5230	    MDI_SUCCESS)) {
5231		SCSI_HBA_LOG((_LOG(3), self, probe, "==> devinfo"));
5232
5233		/*
5234		 * Enumerate under pHCI:
5235		 *
5236		 * Create dynamic SID dchild node. No attempt is made to
5237		 * transfer information (except the addressing and identity
5238		 * information) from the probe node to the dynamic node since
5239		 * there may be HBA specific side effects that the framework
5240		 * does not known how to transfer.
5241		 */
5242		ndi_devi_alloc_sleep(self, nname,
5243		    (se == SE_HP) ? DEVI_SID_HP_NODEID : DEVI_SID_NODEID,
5244		    &dchild);
5245		ASSERT(dchild);
5246		ndi_flavor_set(dchild, SCSA_FLAVOR_SCSI_DEVICE);
5247
5248		/*
5249		 * Decorate new node with addressing properties (via
5250		 * scsi_hba_ua_set()), compatible, identity information, and
5251		 * class.
5252		 */
5253		if ((scsi_hba_ua_set(addr, dchild, NULL) == 0) ||
5254		    (ndi_prop_update_string_array(DDI_DEV_T_NONE, dchild,
5255		    "compatible", compat, ncompat) != DDI_PROP_SUCCESS) ||
5256		    (inq80 && (ndi_prop_update_byte_array(DDI_DEV_T_NONE,
5257		    dchild, "inquiry-page-80", inq80, inq80len) !=
5258		    DDI_PROP_SUCCESS)) ||
5259		    (inq83 && (ndi_prop_update_byte_array(DDI_DEV_T_NONE,
5260		    dchild, "inquiry-page-83", inq83, inq83len) !=
5261		    DDI_PROP_SUCCESS)) ||
5262		    (ndi_prop_update_string(DDI_DEV_T_NONE, dchild,
5263		    "class", "scsi") != DDI_PROP_SUCCESS)) {
5264			SCSI_HBA_LOG((_LOG(2), self, NULL,
5265			    "devinfo @%s failed decoration", addr));
5266			(void) scsi_hba_remove_node(dchild);
5267			dchild = NULL;
5268			goto out;
5269		}
5270
5271		/* Bind the driver */
5272		if (ndi_devi_bind_driver(dchild, 0) != NDI_SUCCESS) {
5273			/* need to bind in order to register a devid */
5274			SCSI_HBA_LOG((_LOGCFG, NULL, dchild,
5275			    "devinfo @%s created, no driver-> "
5276			    "no devid_register", addr));
5277			goto out;
5278		}
5279
5280		/* Register devid */
5281		if (have_devid) {
5282			if (ddi_devid_register(dchild, devid) == DDI_FAILURE)
5283				SCSI_HBA_LOG((_LOG(1), NULL, dchild,
5284				    "devinfo @%s created, "
5285				    "devid register failed", addr));
5286			else
5287				SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5288				    "devinfo @%s created with devid", addr));
5289		} else
5290			SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5291			    "devinfo @%s created, no devid", addr));
5292	} else {
5293		/*
5294		 * Enumerate under vHCI:
5295		 *
5296		 * Create a pathinfo pchild node.
5297		 */
5298		SCSI_HBA_LOG((_LOG(3), self, probe, "==>pathinfo"));
5299
5300		if (mdi_pi_alloc_compatible(self, nname, guid, addr, compat,
5301		    ncompat, 0, &pchild) != MDI_SUCCESS) {
5302			SCSI_HBA_LOG((_LOG(2), self, probe,
5303			    "pathinfo alloc failed"));
5304			goto out;
5305		}
5306
5307		ASSERT(pchild);
5308		dchild = mdi_pi_get_client(pchild);
5309		ASSERT(dchild);
5310		ndi_flavor_set(dchild, SCSA_FLAVOR_SCSI_DEVICE);
5311
5312		/*
5313		 * Decorate new node with addressing properties via
5314		 * scsi_hba_ua_set().
5315		 */
5316		if (scsi_hba_ua_set(addr, NULL, pchild) == 0) {
5317			SCSI_HBA_LOG((_LOG(1), self, NULL,
5318			    "pathinfo %s decoration failed",
5319			    mdi_pi_spathname(pchild)));
5320			(void) mdi_pi_free(pchild, 0);
5321			pchild = NULL;
5322			goto out;
5323		}
5324
5325		/* Bind the driver */
5326		if (ndi_devi_bind_driver(dchild, 0) != NDI_SUCCESS) {
5327			/* need to bind in order to register a devid */
5328			SCSI_HBA_LOG((_LOGCFG, self, NULL,
5329			    "pathinfo %s created, no client driver-> "
5330			    "no devid_register", mdi_pi_spathname(pchild)));
5331			goto out;
5332		}
5333
5334		/* Watch out for inconsistancies in devids. */
5335		if (ddi_devid_get(dchild, &cdevid) == DDI_SUCCESS)
5336			have_cdevid = 1;
5337
5338		if (have_devid && !have_cdevid) {
5339			/* Client does not yet have devid, register ours. */
5340			if (ddi_devid_register(dchild, devid) == DDI_FAILURE)
5341				SCSI_HBA_LOG((_LOG(1), self, NULL,
5342				    "pathinfo %s created, "
5343				    "devid register failed",
5344				    mdi_pi_spathname(pchild)));
5345			else
5346				SCSI_HBA_LOG((_LOG(2), self, NULL,
5347				    "pathinfo %s created with devid",
5348				    mdi_pi_spathname(pchild)));
5349		} else if (have_devid && have_cdevid) {
5350			/*
5351			 * We have devid and client already has devid:
5352			 * they must be the same.
5353			 */
5354			if (ddi_devid_compare(cdevid, devid) != 0) {
5355				SCSI_HBA_LOG((_LOG(WARN), NULL, dchild,
5356				    "mismatched devid on path %s",
5357				    mdi_pi_spathname(pchild)));
5358			}
5359		} else if (!have_devid && have_cdevid) {
5360			/*
5361			 * Client already has a devid, but we don't:
5362			 * we should not have missing devids.
5363			 */
5364			SCSI_HBA_LOG((_LOG(WARN), NULL, dchild,
5365			    "missing devid on path %s",
5366			    mdi_pi_spathname(pchild)));
5367		} else if (!have_cdevid && !have_devid) {
5368			/* devid not supported */
5369			SCSI_HBA_LOG((_LOG(2), self, NULL,
5370			    "pathinfo %s created, no devid",
5371			    mdi_pi_spathname(pchild)));
5372		}
5373
5374		/*
5375		 * The above has registered devid for the device under
5376		 * the client node.  Now register it under the full pHCI
5377		 * path to the device.  We'll get an entry equivalent to
5378		 * booting with mpxio disabled.  This is needed for
5379		 * telemetry during enumeration.
5380		 */
5381		if (e_devid_cache_pathinfo(pchild, devid) == DDI_SUCCESS) {
5382			SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5383			    "pathinfo @%s created with devid", addr));
5384		} else {
5385			SCSI_HBA_LOG((_LOG(1), NULL, dchild,
5386			    "pathinfo @%s devid cache failed", addr));
5387		}
5388	}
5389
5390	/* free the node name and compatible information */
5391out:	if (have_devid)
5392		ddi_devid_free(devid);
5393	if (have_cdevid)
5394		ddi_devid_free(cdevid);
5395	if (guid)
5396		ddi_devid_free_guid(guid);
5397	if (compat)
5398		scsi_hba_ident_nodename_compatible_free(nname, dname, compat);
5399	if (inq80)
5400		ddi_prop_free(inq80);
5401	if (inq83)
5402		ddi_prop_free(inq83);
5403	if (binding_set)
5404		ddi_prop_free(binding_set);
5405
5406	/* return child_type results */
5407	if (pchild) {
5408		*dchildp = NULL;
5409		*pchildp = pchild;
5410		return (CHILD_TYPE_PATHINFO);
5411	} else if (dchild) {
5412		*dchildp = dchild;
5413		*pchildp = NULL;
5414		return (CHILD_TYPE_DEVINFO);
5415	}
5416
5417	return (CHILD_TYPE_NONE);
5418}
5419
5420/*
5421 * Call scsi_device_createchild and then initchild the new node.
5422 */
5423static dev_info_t *
5424scsi_device_configchild(dev_info_t *self, char *addr, scsi_enum_t se,
5425    struct scsi_device *sdprobe, int *circp, int *ppi)
5426{
5427	int		child_type;
5428	dev_info_t	*dchild;
5429	mdi_pathinfo_t	*pchild;
5430	dev_info_t	*child;
5431	int		rval;
5432
5433	ASSERT(self && addr && *addr && DEVI_BUSY_OWNED(self));
5434	if (ppi)
5435		*ppi = 0;
5436
5437	child_type = scsi_device_createchild(self, addr, se, sdprobe,
5438	    &dchild, &pchild);
5439
5440	/*
5441	 * Prevent multiple initialized (tran_tgt_init) nodes associated with
5442	 * the same @addr at the same time by calling tran_tgt_free() on the
5443	 * probe node prior to promotion of the 'real' node.  After the call
5444	 * to scsi_hba_barrier_tran_tgt_free(), the HBA no longer has any
5445	 * probe node context.
5446	 */
5447	scsi_hba_barrier_tran_tgt_free(sdprobe->sd_dev);
5448
5449	switch (child_type) {
5450	case CHILD_TYPE_NONE:
5451		child = NULL;
5452		break;
5453
5454	case CHILD_TYPE_PATHINFO:
5455		/*
5456		 * Online pathinfo: Hold the path and exit the pHCI while
5457		 * calling mdi_pi_online() to avoid deadlock with power
5458		 * management of pHCI.
5459		 */
5460		ASSERT(MDI_PHCI(self));
5461		mdi_hold_path(pchild);
5462		scsi_hba_devi_exit_phci(self, *circp);
5463
5464		rval = mdi_pi_online(pchild, 0);
5465
5466		scsi_hba_devi_enter_phci(self, circp);
5467		mdi_rele_path(pchild);
5468
5469		if (rval != MDI_SUCCESS) {
5470			/* pathinfo form of "failed during tran_tgt_init" */
5471			scsi_enumeration_failed(NULL, se,
5472			    mdi_pi_spathname(pchild), "path online");
5473			(void) mdi_pi_free(pchild, 0);
5474			return (NULL);
5475		}
5476
5477		/*
5478		 * Return the path_instance of the pathinfo node.
5479		 *
5480		 * NOTE: We assume that sd_inq is not path-specific.
5481		 */
5482		if (ppi)
5483			*ppi = mdi_pi_get_path_instance(pchild);
5484
5485
5486		/*
5487		 * Fallthrough into CHILD_TYPE_DEVINFO code to promote
5488		 * the 'client' devinfo node as a dchild.
5489		 */
5490		dchild = mdi_pi_get_client(pchild);
5491		SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5492		    "pathinfo online successful"));
5493		/* FALLTHROUGH */
5494
5495	case CHILD_TYPE_DEVINFO:
5496		/*
5497		 * For now, we ndi_devi_online() the child because some other
5498		 * parts of the IO framework, like degenerate devid code,
5499		 * depend on bus_config driving nodes to DS_ATTACHED. At some
5500		 * point in the future, to keep things light-weight, we would
5501		 * like to change the ndi_devi_online call below to be
5502		 *
5503		 *	if (ddi_initchild(self, dchild) != DDI_SUCCESS)
5504		 *
5505		 * This would promote the node so that framework code could
5506		 * find the child with an @addr search, but does not incur
5507		 * attach(9E) overhead for BUS_CONFIG_ALL cases where the
5508		 * framework is not interested in attach of the node.
5509		 *
5510		 * NOTE: If the addr specified has incorrect syntax (busconfig
5511		 * one of bogus /devices path) then call below can fail.
5512		 */
5513		if (ndi_devi_online(dchild, 0) != NDI_SUCCESS) {
5514			SCSI_HBA_LOG((_LOG(2), NULL, dchild,
5515			    "devinfo online failed"));
5516
5517			/* failed online does not remove the node */
5518			(void) scsi_hba_remove_node(dchild);
5519			return (NULL);
5520		}
5521		SCSI_HBA_LOG((_LOG(4), NULL, dchild,
5522		    "devinfo initchild successful"));
5523		child = dchild;
5524		break;
5525	}
5526	return (child);
5527}
5528
5529void
5530scsi_hba_pkt_comp(struct scsi_pkt *pkt)
5531{
5532	scsi_hba_tran_t	*tran;
5533	uint8_t		*sensep;
5534
5535	ASSERT(pkt);
5536
5537	/*
5538	 * Catch second call on the same packet before doing anything else.
5539	 */
5540	if (pkt->pkt_flags & FLAG_PKT_COMP_CALLED) {
5541		cmn_err(
5542#ifdef DEBUG
5543		    CE_PANIC,
5544#else
5545		    CE_WARN,
5546#endif
5547		    "%s duplicate scsi_hba_pkt_comp(9F) on same scsi_pkt(9S)",
5548		    mod_containing_pc(caller()));
5549	}
5550
5551	pkt->pkt_flags |= FLAG_PKT_COMP_CALLED;
5552
5553	if (pkt->pkt_comp == NULL)
5554		return;
5555
5556	/*
5557	 * For HBA drivers that implement tran_setup_pkt(9E), if we are
5558	 * completing a 'consistent' mode DMA operation then we must
5559	 * perform dma_sync prior to calling pkt_comp to ensure that
5560	 * the target driver sees the correct data in memory.
5561	 */
5562	ASSERT((pkt->pkt_flags & FLAG_NOINTR) == 0);
5563	if (((pkt->pkt_dma_flags & DDI_DMA_CONSISTENT) &&
5564	    (pkt->pkt_dma_flags & DDI_DMA_READ)) &&
5565	    ((P_TO_TRAN(pkt)->tran_setup_pkt) != NULL)) {
5566		scsi_sync_pkt(pkt);
5567	}
5568
5569	/*
5570	 * If the HBA driver is using SCSAv3 scsi_hba_tgtmap_create enumeration
5571	 * then we detect the special ASC/ASCQ completion codes that indicate
5572	 * that the lun configuration of a target has changed. Since we need to
5573	 * be determine scsi_device given scsi_address enbedded in
5574	 * scsi_pkt (via scsi_address_device(9F)), we also require use of
5575	 * SCSI_HBA_ADDR_COMPLEX.
5576	 */
5577	tran = pkt->pkt_address.a_hba_tran;
5578	ASSERT(tran);
5579	if ((tran->tran_tgtmap == NULL) ||
5580	    !(tran->tran_hba_flags & SCSI_HBA_ADDR_COMPLEX))
5581		goto comp;		/* not using tgtmap */
5582
5583	/*
5584	 * Check for lun-change notification and queue the scsi_pkt for
5585	 * lunchg1 processing. The 'pkt_comp' call to the target driver
5586	 * is part of lunchg1 processing.
5587	 */
5588	if ((pkt->pkt_reason == CMD_CMPLT) &&
5589	    (((*pkt->pkt_scbp) & STATUS_MASK) == STATUS_CHECK) &&
5590	    (pkt->pkt_state & STATE_ARQ_DONE)) {
5591		sensep = (uint8_t *)&(((struct scsi_arq_status *)(uintptr_t)
5592		    (pkt->pkt_scbp))->sts_sensedata);
5593		if (((scsi_sense_key(sensep) == KEY_UNIT_ATTENTION) &&
5594		    (scsi_sense_asc(sensep) == 0x3f) &&
5595		    (scsi_sense_ascq(sensep) == 0x0e)) ||
5596
5597		    ((scsi_sense_key(sensep) == KEY_UNIT_ATTENTION) &&
5598		    (scsi_sense_asc(sensep) == 0x25) &&
5599		    (scsi_sense_ascq(sensep) == 0x00))) {
5600			/*
5601			 * The host adaptor is done with the packet, we use
5602			 * pkt_stmp stage-temporary to link the packet for
5603			 * lunchg1 processing.
5604			 *
5605			 * NOTE: pkt_ha_private is not available since its use
5606			 * extends to tran_teardown_pkt.
5607			 */
5608			mutex_enter(&scsi_lunchg1_mutex);
5609			pkt->pkt_stmp = scsi_lunchg1_list;
5610			scsi_lunchg1_list = pkt;
5611			if (pkt->pkt_stmp == NULL)
5612				(void) cv_signal(&scsi_lunchg1_cv);
5613			mutex_exit(&scsi_lunchg1_mutex);
5614			return;
5615		}
5616	}
5617
5618comp:	(*pkt->pkt_comp)(pkt);
5619}
5620
5621/*
5622 * return 1 if the specified node is a barrier/probe node
5623 */
5624static int
5625scsi_hba_devi_is_barrier(dev_info_t *probe)
5626{
5627	if (probe && (strcmp(ddi_node_name(probe), "probe") == 0))
5628		return (1);
5629	return (0);
5630}
5631
5632/*
5633 * A host adapter driver is easier to write if we prevent multiple initialized
5634 * (tran_tgt_init) scsi_device structures to the same unit-address at the same
5635 * time.  We prevent this from occurring all the time during the barrier/probe
5636 * node to real child hand-off by calling scsi_hba_barrier_tran_tgt_free
5637 * on the probe node prior to ddi_inichild of the 'real' node.  As part of
5638 * this early tran_tgt_free implementation, we must also call this function
5639 * as we put a probe node on the scsi_hba_barrier_list.
5640 */
5641static void
5642scsi_hba_barrier_tran_tgt_free(dev_info_t *probe)
5643{
5644	struct scsi_device	*sdprobe;
5645	dev_info_t		*self;
5646	scsi_hba_tran_t		*tran;
5647
5648	ASSERT(probe && scsi_hba_devi_is_barrier(probe));
5649
5650	/* Return if we never called tran_tgt_init(9E). */
5651	if (i_ddi_node_state(probe) < DS_INITIALIZED)
5652		return;
5653
5654	sdprobe = ddi_get_driver_private(probe);
5655	self = ddi_get_parent(probe);
5656	ASSERT(sdprobe && self);
5657	tran = ddi_get_driver_private(self);
5658	ASSERT(tran);
5659
5660	if (tran->tran_tgt_free) {
5661		/*
5662		 * To correctly support TRAN_CLONE, we need to use the same
5663		 * cloned scsi_hba_tran(9S) structure for both tran_tgt_init(9E)
5664		 * and tran_tgt_free(9E).
5665		 */
5666		if (tran->tran_hba_flags & SCSI_HBA_TRAN_CLONE)
5667			tran = sdprobe->sd_address.a_hba_tran;
5668
5669		if (!sdprobe->sd_tran_tgt_free_done) {
5670			SCSI_HBA_LOG((_LOG(4), NULL, probe,
5671			    "tran_tgt_free EARLY"));
5672			(*tran->tran_tgt_free) (self, probe, tran, sdprobe);
5673			sdprobe->sd_tran_tgt_free_done = 1;
5674		} else {
5675			SCSI_HBA_LOG((_LOG(4), NULL, probe,
5676			    "tran_tgt_free EARLY already done"));
5677		}
5678	}
5679}
5680
5681/*
5682 * Add an entry to the list of barrier nodes to be asynchronously deleted by
5683 * the scsi_hba_barrier_daemon after the specified timeout. Nodes on
5684 * the barrier list are used to implement the bus_config probe cache
5685 * of non-existent devices. The nodes are at DS_INITIALIZED, so their
5686 * @addr is established for searching. Since devi_ref of a DS_INITIALIZED
5687 * node will *not* prevent demotion, demotion is prevented by setting
5688 * sd_uninit_prevent. Devinfo snapshots attempt to attach probe cache
5689 * nodes, and on failure attempt to demote the node (without the participation
5690 * of bus_unconfig) to DS_BOUND - this demotion is prevented via
5691 * sd_uninit_prevent causing any attempted DDI_CTLOPS_UNINITCHILD to fail.
5692 * Probe nodes are bound to nulldriver. The list is sorted by
5693 * expiration time.
5694 *
5695 * NOTE: If we drove a probe node to DS_ATTACHED, we could use ndi_hold_devi()
5696 * to prevent demotion (instead of sd_uninit_prevent).
5697 */
5698static void
5699scsi_hba_barrier_add(dev_info_t *probe, int seconds)
5700{
5701	struct scsi_hba_barrier	*nb;
5702	struct scsi_hba_barrier	*b;
5703	struct scsi_hba_barrier	**bp;
5704	clock_t			endtime;
5705
5706	ASSERT(scsi_hba_devi_is_barrier(probe));
5707
5708	/* HBA is no longer responsible for nodes on the barrier list. */
5709	scsi_hba_barrier_tran_tgt_free(probe);
5710	nb = kmem_alloc(sizeof (struct scsi_hba_barrier), KM_SLEEP);
5711	mutex_enter(&scsi_hba_barrier_mutex);
5712	endtime = ddi_get_lbolt() + drv_usectohz(seconds * MICROSEC);
5713	for (bp = &scsi_hba_barrier_list; (b = *bp) != NULL;
5714	    bp = &b->barrier_next)
5715		if (b->barrier_endtime > endtime)
5716			break;
5717	nb->barrier_next = *bp;
5718	nb->barrier_endtime = endtime;
5719	nb->barrier_probe = probe;
5720	*bp = nb;
5721	if (bp == &scsi_hba_barrier_list)
5722		(void) cv_signal(&scsi_hba_barrier_cv);
5723	mutex_exit(&scsi_hba_barrier_mutex);
5724}
5725
5726/*
5727 * Attempt to remove devinfo node node, return 1 if removed. We
5728 * don't try to remove barrier nodes that have sd_uninit_prevent set
5729 * (even though they should fail device_uninitchild).
5730 */
5731static int
5732scsi_hba_remove_node(dev_info_t *child)
5733{
5734	dev_info_t		*self = ddi_get_parent(child);
5735	struct scsi_device	*sd;
5736	int			circ;
5737	int			remove = 1;
5738	int			ret = 0;
5739	char			na[SCSI_MAXNAMELEN];
5740
5741	scsi_hba_devi_enter(self, &circ);
5742
5743	/* Honor sd_uninit_prevent on barrier nodes */
5744	if (scsi_hba_devi_is_barrier(child)) {
5745		sd = ddi_get_driver_private(child);
5746		if (sd && sd->sd_uninit_prevent)
5747			remove = 0;
5748	}
5749
5750	if (remove) {
5751		(void) ddi_deviname(child, na);
5752		if (ddi_remove_child(child, 0) != DDI_SUCCESS) {
5753			SCSI_HBA_LOG((_LOG(2), NULL, child,
5754			    "remove_node failed"));
5755		} else {
5756			child = NULL;		/* child is gone */
5757			SCSI_HBA_LOG((_LOG(4), self, NULL,
5758			    "remove_node removed %s", *na ? &na[1] : na));
5759			ret = 1;
5760		}
5761	} else {
5762		SCSI_HBA_LOG((_LOG(4), NULL, child, "remove_node prevented"));
5763	}
5764	scsi_hba_devi_exit(self, circ);
5765	return (ret);
5766}
5767
5768/*
5769 * The asynchronous barrier deletion daemon. Waits for a barrier timeout
5770 * to expire, then deletes the barrier (removes it as a child).
5771 */
5772/*ARGSUSED*/
5773static void
5774scsi_hba_barrier_daemon(void *arg)
5775{
5776	struct scsi_hba_barrier	*b;
5777	dev_info_t		*probe;
5778	callb_cpr_t		cprinfo;
5779	int			circ;
5780	dev_info_t		*self;
5781
5782	CALLB_CPR_INIT(&cprinfo, &scsi_hba_barrier_mutex,
5783	    callb_generic_cpr, "scsi_hba_barrier_daemon");
5784again:	mutex_enter(&scsi_hba_barrier_mutex);
5785	for (;;) {
5786		b = scsi_hba_barrier_list;
5787		if (b == NULL) {
5788			/* all barriers expired, wait for barrier_add */
5789			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5790			(void) cv_wait(&scsi_hba_barrier_cv,
5791			    &scsi_hba_barrier_mutex);
5792			CALLB_CPR_SAFE_END(&cprinfo, &scsi_hba_barrier_mutex);
5793		} else {
5794			if (ddi_get_lbolt() >= b->barrier_endtime) {
5795				/*
5796				 * Drop and retry if ordering issue. Do this
5797				 * before calling scsi_hba_remove_node() and
5798				 * deadlocking.
5799				 */
5800				probe = b->barrier_probe;
5801				self = ddi_get_parent(probe);
5802				if (scsi_hba_devi_tryenter(self, &circ) == 0) {
5803delay:					mutex_exit(&scsi_hba_barrier_mutex);
5804					delay_random(5);
5805					goto again;
5806				}
5807
5808				/* process expired barrier */
5809				if (!scsi_hba_remove_node(probe)) {
5810					/* remove failed, delay and retry */
5811					SCSI_HBA_LOG((_LOG(4), NULL, probe,
5812					    "delay expire"));
5813					scsi_hba_devi_exit(self, circ);
5814					goto delay;
5815				}
5816				scsi_hba_barrier_list = b->barrier_next;
5817				kmem_free(b, sizeof (struct scsi_hba_barrier));
5818				scsi_hba_devi_exit(self, circ);
5819			} else {
5820				/* establish timeout for next barrier expire */
5821				(void) cv_timedwait(&scsi_hba_barrier_cv,
5822				    &scsi_hba_barrier_mutex,
5823				    b->barrier_endtime);
5824			}
5825		}
5826	}
5827}
5828
5829/*
5830 * Remove all barriers associated with the specified HBA. This is called
5831 * from from the bus_unconfig implementation to remove probe nodes associated
5832 * with the specified HBA (self) so that probe nodes that have not expired
5833 * will not prevent DR of the HBA.
5834 */
5835static void
5836scsi_hba_barrier_purge(dev_info_t *self)
5837{
5838	struct scsi_hba_barrier	**bp;
5839	struct scsi_hba_barrier	*b;
5840
5841	mutex_enter(&scsi_hba_barrier_mutex);
5842	for (bp = &scsi_hba_barrier_list; (b = *bp) != NULL; ) {
5843		if (ddi_get_parent(b->barrier_probe) == self) {
5844			if (scsi_hba_remove_node(b->barrier_probe)) {
5845				*bp = b->barrier_next;
5846				kmem_free(b, sizeof (struct scsi_hba_barrier));
5847			} else {
5848				SCSI_HBA_LOG((_LOG(4), NULL, b->barrier_probe,
5849				    "skip purge"));
5850			}
5851		} else
5852			bp = &b->barrier_next;
5853	}
5854
5855	mutex_exit(&scsi_hba_barrier_mutex);
5856}
5857
5858/*
5859 * LUN-change processing daemons: processing occurs in two stages:
5860 *
5861 * Stage 1:	Daemon waits for a lunchg1 queued scsi_pkt, dequeues the pkt,
5862 *		forms the path, completes the scsi_pkt (pkt_comp), and
5863 *		queues the path for stage 2 processing. The use of stage 1
5864 *		avoids issues related to memory allocation in interrupt context
5865 *		(scsi_hba_pkt_comp()). We delay the pkt_comp completion until
5866 *		after lunchg1 processing forms the path for stage 2 - this is
5867 *		done to prevent the target driver from detaching until the
5868 *		path formation is complete (driver with outstanding commands
5869 *		should not detach).
5870 *
5871 * Stage 2:	Daemon waits for a lunchg2 queued request, dequeues the
5872 *		request, and opens the path using ldi_open_by_name(). The
5873 *		path opened uses a special "@taddr,*" unit address that will
5874 *		trigger lun enumeration in scsi_hba_bus_configone(). We
5875 *		trigger lun enumeration in stage 2 to avoid problems when
5876 *		initial ASC/ASCQ trigger occurs during discovery.
5877 */
5878/*ARGSUSED*/
5879static void
5880scsi_lunchg1_daemon(void *arg)
5881{
5882	callb_cpr_t		cprinfo;
5883	struct scsi_pkt		*pkt;
5884	scsi_hba_tran_t		*tran;
5885	dev_info_t		*self;
5886	struct scsi_device	*sd;
5887	char			*ua, *p;
5888	char			taddr[SCSI_MAXNAMELEN];
5889	char			path[MAXPATHLEN];
5890	struct scsi_lunchg2	*lunchg2;
5891
5892	CALLB_CPR_INIT(&cprinfo, &scsi_lunchg1_mutex,
5893	    callb_generic_cpr, "scsi_lunchg1_daemon");
5894	mutex_enter(&scsi_lunchg1_mutex);
5895	for (;;) {
5896		pkt = scsi_lunchg1_list;
5897		if (pkt == NULL) {
5898			/* All lunchg1 processing requests serviced, wait. */
5899			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5900			(void) cv_wait(&scsi_lunchg1_cv,
5901			    &scsi_lunchg1_mutex);
5902			CALLB_CPR_SAFE_END(&cprinfo, &scsi_lunchg1_mutex);
5903			continue;
5904		}
5905
5906		/* Unlink and perform lunchg1 processing on pkt. */
5907		scsi_lunchg1_list = pkt->pkt_stmp;
5908
5909		/* Determine initiator port (self) from the pkt_address. */
5910		tran = pkt->pkt_address.a_hba_tran;
5911		ASSERT(tran && tran->tran_tgtmap && tran->tran_iport_dip);
5912		self = tran->tran_iport_dip;
5913
5914		/*
5915		 * Determine scsi_devie from pkt_address (depends on
5916		 * SCSI_HBA_ADDR_COMPLEX).
5917		 */
5918		sd = scsi_address_device(&(pkt->pkt_address));
5919		ASSERT(sd);
5920		if (sd == NULL) {
5921			(*pkt->pkt_comp)(pkt);
5922			continue;
5923		}
5924
5925		/* Determine unit-address from scsi_device. */
5926		ua = scsi_device_unit_address(sd);
5927
5928		/* Extract taddr from the unit-address. */
5929		for (p = taddr; (*ua != ',') && (*ua != '\0'); )
5930			*p++ = *ua++;
5931		*p = '\0';			/* NULL terminate taddr */
5932
5933		/*
5934		 * Form path using special "@taddr,*" notation to trigger
5935		 * lun enumeration.
5936		 */
5937		(void) ddi_pathname(self, path);
5938		(void) strcat(path, "/luns@");
5939		(void) strcat(path, taddr);
5940		(void) strcat(path, ",*");
5941
5942		/*
5943		 * Now that we have the path, complete the pkt that
5944		 * triggered lunchg1 processing.
5945		 */
5946		(*pkt->pkt_comp)(pkt);
5947
5948		/* Allocate element for stage2 processing queue. */
5949		lunchg2 = kmem_alloc(sizeof (*lunchg2), KM_SLEEP);
5950		lunchg2->lunchg2_path = strdup(path);
5951
5952		/* Queue and dispatch to stage 2. */
5953		SCSI_HBA_LOG((_LOG(2), self, NULL,
5954		    "lunchg stage1: queue %s", lunchg2->lunchg2_path));
5955		mutex_enter(&scsi_lunchg2_mutex);
5956		lunchg2->lunchg2_next = scsi_lunchg2_list;
5957		scsi_lunchg2_list = lunchg2;
5958		if (lunchg2->lunchg2_next == NULL)
5959			(void) cv_signal(&scsi_lunchg2_cv);
5960		mutex_exit(&scsi_lunchg2_mutex);
5961	}
5962}
5963
5964/*ARGSUSED*/
5965static void
5966scsi_lunchg2_daemon(void *arg)
5967{
5968	callb_cpr_t		cprinfo;
5969	struct scsi_lunchg2	*lunchg2;
5970	ldi_ident_t		li;
5971	ldi_handle_t		lh;
5972
5973	CALLB_CPR_INIT(&cprinfo, &scsi_lunchg2_mutex,
5974	    callb_generic_cpr, "scsi_lunchg2_daemon");
5975
5976	li = ldi_ident_from_anon();
5977	mutex_enter(&scsi_lunchg2_mutex);
5978	for (;;) {
5979		lunchg2 = scsi_lunchg2_list;
5980		if (lunchg2 == NULL) {
5981			/* All lunchg2 processing requests serviced, wait. */
5982			CALLB_CPR_SAFE_BEGIN(&cprinfo);
5983			(void) cv_wait(&scsi_lunchg2_cv,
5984			    &scsi_lunchg2_mutex);
5985			CALLB_CPR_SAFE_END(&cprinfo, &scsi_lunchg2_mutex);
5986			continue;
5987		}
5988
5989		/* Unlink and perform lunchg2 processing on pkt. */
5990		scsi_lunchg2_list = lunchg2->lunchg2_next;
5991
5992		/*
5993		 * Open and close the path to trigger lun enumeration.  We
5994		 * don't expect the open to succeed, but we do expect code in
5995		 * scsi_hba_bus_configone() to trigger lun enumeration.
5996		 */
5997		SCSI_HBA_LOG((_LOG(2), NULL, NULL,
5998		    "lunchg stage2: open %s", lunchg2->lunchg2_path));
5999		if (ldi_open_by_name(lunchg2->lunchg2_path,
6000		    FREAD, kcred, &lh, li) == 0)
6001			(void) ldi_close(lh, FREAD, kcred);
6002
6003		/* Free path and linked element. */
6004		strfree(lunchg2->lunchg2_path);
6005		kmem_free(lunchg2, sizeof (*lunchg2));
6006	}
6007}
6008
6009/*
6010 * Enumerate a child at the specified @addr. If a device exists @addr then
6011 * ensure that we have the appropriately named devinfo node for it. Name is
6012 * NULL in the bus_config_all case. This routine has no knowledge of the
6013 * format of an @addr string or associated addressing properties.
6014 *
6015 * The caller must guarantee that there is an open scsi_hba_devi_enter on the
6016 * parent. We return the scsi_device structure for the child device. This
6017 * scsi_device structure is valid until the caller scsi_hba_devi_exit the
6018 * parent. The caller can add do ndi_hold_devi of the child prior to the
6019 * scsi_hba_devi_exit to extend the validity of the child.
6020 *
6021 * In some cases the returned scsi_device structure may be used to drive
6022 * additional SCMD_REPORT_LUNS operations by bus_config_all callers.
6023 *
6024 * The first operation performed is to see if there is a dynamic SID nodes
6025 * already attached at the specified "name@addr". This is the fastpath
6026 * case for resolving a reference to a node that has already been created.
6027 * All other references are serialized for a given @addr prior to probing
6028 * to determine the type of device, if any, at the specified @addr.
6029 * If no device is present then NDI_FAILURE is returned. The fact that a
6030 * device does not exist may be determined via the barrier/probe cache,
6031 * minimizing the probes of non-existent devices.
6032 *
6033 * When there is a device present the dynamic SID node is created based on
6034 * the device found. If a driver.conf node exists for the same @addr it
6035 * will either merge into the dynamic SID node (if the SID node bound to
6036 * that driver), or exist independently. To prevent the actions of one driver
6037 * causing side effects in another, code prevents multiple SID nodes from
6038 * binding to the same "@addr" at the same time. There is autodetach code
6039 * to allow one device to be replaced with another at the same @addr for
6040 * slot addressed SCSI bus implementations (SPI). For compatibility with
6041 * legacy driver.conf behavior, the code does not prevent multiple driver.conf
6042 * nodes from attaching to the same @addr at the same time.
6043 *
6044 * This routine may have the side effect of creating nodes for devices other
6045 * than the one being sought. It is possible that there is a different type of
6046 * target device at that target/lun address than we were asking for. In that
6047 * It is the caller's responsibility to determine whether the device we found,
6048 * if any, at the specified address, is the one it really wanted.
6049 */
6050static struct scsi_device *
6051scsi_device_config(dev_info_t *self, char *name, char *addr, scsi_enum_t se,
6052    int *circp, int *ppi)
6053{
6054	dev_info_t		*child = NULL;
6055	dev_info_t		*probe = NULL;
6056	struct scsi_device	*sdchild;
6057	struct scsi_device	*sdprobe;
6058	dev_info_t		*dsearch;
6059	mdi_pathinfo_t		*psearch;
6060	major_t			major;
6061	int			sp;
6062	int			pi = 0;
6063	int			wait_msg = scsi_hba_wait_msg;
6064	int			chg;
6065
6066	ASSERT(self && addr && DEVI_BUSY_OWNED(self));
6067
6068	SCSI_HBA_LOG((_LOG(4), self, NULL, "%s@%s wanted",
6069	    name ? name : "", addr));
6070
6071	/* playing with "probe" node name is dangerous */
6072	if (name && (strcmp(name, "probe") == 0))
6073		return (NULL);
6074
6075	/*
6076	 * NOTE: use 'goto done;' or 'goto fail;'. There should only be one
6077	 * 'return' statement from here to the end of the function - the one
6078	 * on the last line of the function.
6079	 */
6080
6081	/*
6082	 * Fastpath: search to see if we are requesting a named SID node that
6083	 * already exists (we already created) - probe node does not count.
6084	 * scsi_findchild() does not hold the returned devinfo node, but
6085	 * this is OK since the caller has a scsi_hba_devi_enter on the
6086	 * attached parent HBA (self). The caller is responsible for attaching
6087	 * and placing a hold on the child (directly via ndi_hold_devi or
6088	 * indirectly via ndi_busop_bus_config) before doing an
6089	 * scsi_hba_devi_exit on the parent.
6090	 *
6091	 * NOTE: This fastpath prevents detecting a driver binding change
6092	 * (autodetach) if the same nodename is used for old and new binding.
6093	 */
6094	/* first call is with init set */
6095	(void) scsi_findchild(self, name, addr, 1, &dsearch, NULL, &pi);
6096	if (dsearch && scsi_hba_dev_is_sid(dsearch) &&
6097	    !scsi_hba_devi_is_barrier(dsearch)) {
6098		SCSI_HBA_LOG((_LOG(4), NULL, dsearch,
6099		    "%s@%s devinfo fastpath", name ? name : "", addr));
6100		child = dsearch;
6101		goto done;
6102	}
6103
6104	/*
6105	 * Create a barrier devinfo node used to "probe" the device with. We
6106	 * need to drive this node to DS_INITIALIZED so that the
6107	 * DDI_CTLOPS_INITCHILD has occurred, bringing the SCSA transport to
6108	 * a state useable state for issuing our "probe" commands. We establish
6109	 * this barrier node with a node name of "probe" and compatible
6110	 * property of "scsiprobe". The compatible property must be associated
6111	 * in /etc/driver_aliases with a scsi target driver available in the
6112	 * root file system (sd).
6113	 *
6114	 * The "probe" that we perform on the barrier node, after it is
6115	 * DS_INITIALIZED, is used to find the information needed to create a
6116	 * dynamic devinfo (SID) node. This "probe" is separate from the
6117	 * probe(9E) call associated with the transition of a node from
6118	 * DS_INITIALIZED to DS_PROBED. The probe(9E) call that eventually
6119	 * occurs against the created SID node should find ddi_dev_is_sid and
6120	 * just return DDI_PROBE_DONTCARE.
6121	 *
6122	 * Trying to avoid the use of a barrier node is not a good idea
6123	 * because we may have an HBA driver that uses generic bus_config
6124	 * (this code) but implements its own DDI_CTLOPS_INITCHILD with side
6125	 * effects that we can't duplicate (such as the ATA nexus driver).
6126	 *
6127	 * The probe/barrier node plays an integral part of the locking scheme.
6128	 * The objective is to single thread probes of the same device (same
6129	 * @addr) while allowing parallelism for probes of different devices
6130	 * with the same parent. At this point we are serialized on our self.
6131	 * For parallelism we will need to release our self. Prior to release
6132	 * we construct a barrier for probes of the same device to serialize
6133	 * against. The "probe@addr" node acts as this barrier. An entering
6134	 * thread must wait until the probe node does not exist - it can then
6135	 * create and link the probe node - dropping the HBA (self) lock after
6136	 * the node is linked and visible (after ddi_initchild). A side effect
6137	 * of this is that transports should not "go over the wire" (i.e. do
6138	 * things that incur significant delays) until after tran_target_init.
6139	 * This means that the first "over the wire" operation should occur
6140	 * at tran_target_probe time - when things are running in parallel
6141	 * again.
6142	 *
6143	 * If the probe node exists then another probe with the same @addr is
6144	 * in progress, we must wait until there is no probe in progress
6145	 * before proceeding, and when we proceed we must continue to hold the
6146	 * HBA (self) until we have linked a new probe node as a barrier.
6147	 *
6148	 * When a device is found to *not* exist, its probe/barrier node may be
6149	 * marked with DEVICE_REMOVED with node deletion scheduled for some
6150	 * future time (seconds). This asynchronous deletion allows the
6151	 * framework to detect repeated requests to the same non-existent
6152	 * device and avoid overhead associated with contacting a non-existent
6153	 * device again and again.
6154	 */
6155	for (;;) {
6156		/*
6157		 * Search for probe node - they should only exist as devinfo
6158		 * nodes.
6159		 */
6160		(void) scsi_findchild(self, "probe", addr,
6161		    0, &probe, &psearch, NULL);
6162		if (probe == NULL) {
6163			if (psearch)
6164				SCSI_HBA_LOG((_LOG(2), self,
6165				    mdi_pi_get_client(psearch),
6166				    "???? @%s 'probe' search found "
6167				    "pathinfo: %p", addr, (void *)psearch));
6168			break;
6169		}
6170
6171		/*
6172		 * The barrier node may cache the non-existence of a device
6173		 * by leaving the barrier node in place (with
6174		 * DEVI_DEVICE_REMOVED flag set ) for some amount of time after
6175		 * the failure of a probe. This flag is used to fail
6176		 * additional probes until the barrier probe node is deleted,
6177		 * which will occur from a timeout some time after a failed
6178		 * probe. The failed probe will use DEVI_SET_DEVICE_REMOVED
6179		 * and schedule probe node deletion from a timeout. The callers
6180		 * scsi_hba_devi_exit on the way out of the first failure will
6181		 * do the cv_broadcast associated with the cv_wait below - this
6182		 * handles threads that wait prior to DEVI_DEVICE_REMOVED being
6183		 * set.
6184		 */
6185		if (DEVI_IS_DEVICE_REMOVED(probe)) {
6186			SCSI_HBA_LOG((_LOG(3), NULL, probe,
6187			    "detected probe DEVICE_REMOVED"));
6188			probe = NULL;	/* deletion already scheduled */
6189			goto fail;
6190		}
6191
6192		/*
6193		 * Drop the lock on the HBA (self) and wait until the probe in
6194		 * progress has completed. A changes in the sibling list from
6195		 * removing the probe node will cause cv_wait to return
6196		 * (scsi_hba_devi_exit does the cv_broadcast).
6197		 */
6198		if (wait_msg) {
6199			wait_msg--;
6200			SCSI_HBA_LOG((_LOG(2), NULL, probe,
6201			    "exists, probe already in progress: %s", wait_msg ?
6202			    "waiting..." : "last msg, but still waiting..."));
6203		}
6204
6205		/*
6206		 * NOTE: we could avoid rare case of one second delay by
6207		 * implementing scsi_hba_devi_exit_and_wait based on
6208		 * ndi/mdi_devi_exit_and_wait (and consider switching devcfg.c
6209		 * code to use these ndi/mdi interfaces too).
6210		 */
6211		scsi_hba_devi_exit(self, *circp);
6212		mutex_enter(&DEVI(self)->devi_lock);
6213		(void) cv_timedwait(&DEVI(self)->devi_cv,
6214		    &DEVI(self)->devi_lock,
6215		    ddi_get_lbolt() + drv_usectohz(MICROSEC));
6216		mutex_exit(&DEVI(self)->devi_lock);
6217		scsi_hba_devi_enter(self, circp);
6218	}
6219	ASSERT(probe == NULL);
6220
6221	/*
6222	 * Search to see if we are requesting a SID node that already exists.
6223	 * We hold the HBA (self) and there is not another probe in progress at
6224	 * the same @addr. scsi_findchild() does not hold the returned
6225	 * devinfo node but this is OK since we hold the HBA (self).
6226	 */
6227	if (name) {
6228		(void) scsi_findchild(self, name, addr, 1, &dsearch, NULL, &pi);
6229		if (dsearch && scsi_hba_dev_is_sid(dsearch)) {
6230			SCSI_HBA_LOG((_LOG(4), NULL, dsearch,
6231			    "%s@%s probe devinfo fastpath",
6232			    name ? name : "", addr));
6233			child = dsearch;
6234			goto done;
6235		}
6236	}
6237
6238	/*
6239	 * We are looking for a SID node that does not exist or a driver.conf
6240	 * node.
6241	 *
6242	 * To avoid probe side effects, before we probe the device at the
6243	 * specified address we need to check to see if there is already an
6244	 * initialized child "@addr".
6245	 *
6246	 * o If we find an initialized SID child and name is NULL or matches
6247	 *   the name or the name of the attached driver then we return the
6248	 *   existing node.
6249	 *
6250	 * o If we find a non-matching SID node, we will attempt to autodetach
6251	 *   and remove the node in preference to our new node.
6252	 *
6253	 * o If SID node found does not match and can't be autodetached, we
6254	 *   fail: we only allow one SID node at an address.
6255	 *
6256	 * NOTE: This code depends on SID nodes showing up prior to
6257	 * driver.conf nodes in the sibling list.
6258	 */
6259	for (;;) {
6260		/* first NULL name call is with init set */
6261		(void) scsi_findchild(self, NULL, addr, 1, &dsearch, NULL, &pi);
6262		if (dsearch == NULL)
6263			break;
6264		ASSERT(!scsi_hba_devi_is_barrier(dsearch));
6265
6266		/*
6267		 * To detect changes in driver binding that should attempt
6268		 * autodetach we determine the major number of the driver
6269		 * that should currently be associated with the device based
6270		 * on the compatible property.
6271		 */
6272		major = DDI_MAJOR_T_NONE;
6273		if (scsi_hba_dev_is_sid(dsearch))
6274			major = ddi_compatible_driver_major(dsearch, NULL);
6275		if ((major == DDI_MAJOR_T_NONE) && (name == NULL))
6276			major = ddi_driver_major(dsearch);
6277
6278		if ((scsi_hba_dev_is_sid(dsearch) ||
6279		    (i_ddi_node_state(dsearch) >= DS_INITIALIZED)) &&
6280		    ((name == NULL) ||
6281		    (strcmp(ddi_node_name(dsearch), name) == 0) ||
6282		    (strcmp(ddi_driver_name(dsearch), name) == 0)) &&
6283		    (major == ddi_driver_major(dsearch))) {
6284			SCSI_HBA_LOG((_LOG(3), NULL, dsearch,
6285			    "already attached @addr"));
6286			child = dsearch;
6287			goto done;
6288		}
6289
6290		if (!scsi_hba_dev_is_sid(dsearch))
6291			break;			/* driver.conf node */
6292
6293		/*
6294		 * Implement autodetach of SID node for situations like a
6295		 * previously "scsinodev" LUN0 coming into existence (or a
6296		 * disk/tape on an SPI transport at same addr but never both
6297		 * powered on at the same time). Try to autodetach the existing
6298		 * SID node @addr. If that works, search again - otherwise fail.
6299		 */
6300		SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6301		    "looking for %s@%s: SID @addr exists, autodetach",
6302		    name ? name : "", addr));
6303		if (!scsi_hba_remove_node(dsearch)) {
6304			SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6305			    "autodetach @%s failed: fail %s@%s",
6306			    addr, name ? name : "", addr));
6307			goto fail;
6308		}
6309		SCSI_HBA_LOG((_LOG(2), self, NULL, "autodetach @%s OK", addr));
6310	}
6311
6312	/*
6313	 * We will be creating a new SID node, allocate probe node
6314	 * used to find out information about the device located @addr.
6315	 * The probe node also acts as a barrier against additional
6316	 * configuration at the same address, and in the case of non-existent
6317	 * devices it will (for some amount of time) avoid re-learning that
6318	 * the device does not exist on every reference. Once the probe
6319	 * node is DS_LINKED we can drop the HBA (self).
6320	 *
6321	 * The probe node is allocated as a hidden node so that it does not
6322	 * show up in devinfo snapshots.
6323	 */
6324	ndi_devi_alloc_sleep(self, "probe",
6325	    (se == SE_HP) ? DEVI_SID_HP_HIDDEN_NODEID : DEVI_SID_HIDDEN_NODEID,
6326	    &probe);
6327	ASSERT(probe);
6328	ndi_flavor_set(probe, SCSA_FLAVOR_SCSI_DEVICE);
6329
6330	/*
6331	 * Decorate the probe node with the property representation of @addr
6332	 * unit-address string prior to initchild so that initchild can
6333	 * construct the name of the node from properties and tran_tgt_init
6334	 * implementation can determine what LUN is being referenced.
6335	 *
6336	 * If the addr specified has incorrect syntax (busconfig one of bogus
6337	 * /devices path) then scsi_hba_ua_set can fail.  If the address
6338	 * is not understood by the SCSA HBA driver then this operation will
6339	 * work, but tran_tgt_init may still fail (for example the HBA
6340	 * driver may not support secondary functions).
6341	 */
6342	if (scsi_hba_ua_set(addr, probe, NULL) == 0) {
6343		SCSI_HBA_LOG((_LOG(2), NULL, probe,
6344		    "@%s failed scsi_hba_ua_set", addr));
6345		goto fail;
6346	}
6347
6348	/*
6349	 * Set the class property to "scsi". This is sufficient to distinguish
6350	 * the node for HBAs that have multiple classes of children (like uata
6351	 * - which has "dada" class for ATA children and "scsi" class for
6352	 * ATAPI children) and may not use our scsi_busctl_initchild()
6353	 * implementation. We also add a "compatible" property of "scsiprobe"
6354	 * to select the probe driver.
6355	 */
6356	if ((ndi_prop_update_string(DDI_DEV_T_NONE, probe,
6357	    "class", "scsi") != DDI_PROP_SUCCESS) ||
6358	    (ndi_prop_update_string_array(DDI_DEV_T_NONE, probe,
6359	    "compatible", &compatible_probe, 1) != DDI_PROP_SUCCESS)) {
6360		SCSI_HBA_LOG((_LOG(1), NULL, probe,
6361		    "@%s failed node decoration", addr));
6362		goto fail;
6363	}
6364
6365	/*
6366	 * Promote probe node to DS_INITIALIZED so that transport can be used
6367	 * for scsi_probe. After this the node is linked and visible as a
6368	 * barrier for serialization of other @addr operations.
6369	 *
6370	 * NOTE: If we attached the probe node, we could get rid of
6371	 * uninit_prevent.
6372	 */
6373	if (ddi_initchild(self, probe) != DDI_SUCCESS) {
6374		SCSI_HBA_LOG((_LOG(2), NULL, probe,
6375		    "@%s failed initchild", addr));
6376
6377		/* probe node will be removed in fail exit path */
6378		goto fail;
6379	}
6380
6381	/* get the scsi_device structure of the probe node */
6382	sdprobe = ddi_get_driver_private(probe);
6383	ASSERT(sdprobe);
6384
6385	/*
6386	 * Do scsi_probe. The probe node is linked and visible as a barrier.
6387	 * We prevent uninitialization of the probe node and drop our HBA (self)
6388	 * while we run scsi_probe() of this "@addr". This allows the framework
6389	 * to support multiple scsi_probes for different devices attached to
6390	 * the same HBA (self) in parallel. We prevent node demotion of the
6391	 * probe node from DS_INITIALIZED by setting sd_uninit_prevent. The
6392	 * probe node can not be successfully demoted below DS_INITIALIZED
6393	 * (scsi_busctl_uninitchild will fail) until we zero sd_uninit_prevent
6394	 * as we are freeing the node via scsi_hba_remove_node(probe).
6395	 */
6396	sdprobe->sd_uninit_prevent++;
6397	scsi_hba_devi_exit(self, *circp);
6398	sp = scsi_probe(sdprobe, SLEEP_FUNC);
6399
6400	/* Introduce a small delay here to increase parallelism. */
6401	delay_random(5);
6402
6403	if (sp == SCSIPROBE_EXISTS) {
6404		/*
6405		 * For a device that exists, while still running in parallel,
6406		 * also get identity information from device. This is done
6407		 * separate from scsi_probe/tran_tgt_probe/scsi_hba_probe
6408		 * since the probe code path may still be used for HBAs
6409		 * that don't use common bus_config services (we don't want
6410		 * to expose that code path to a behavior change). This
6411		 * operation is called 'identity' to avoid confusion with
6412		 * deprecated identify(9E).
6413		 *
6414		 * Future: We may eventually want to allow HBA customization via
6415		 * scsi_identity/tran_tgt_identity/scsi_device_identity, but for
6416		 * now we just scsi_device_identity.
6417		 *
6418		 * The identity operation will establish additional properties
6419		 * on the probe node related to device identity:
6420		 *
6421		 *	"inquiry-page-80"	byte array of SCSI page 80
6422		 *	"inquiry-page-83"	byte array of SCSI page 83
6423		 *
6424		 * These properties will be used to generate a devid
6425		 * (ddi_devid_scsi_encode) and guid - and to register
6426		 * (ddi_devid_register) a devid for the device.
6427		 *
6428		 * If identify fails (non-zero return), the we had allocation
6429		 * problems or the device returned inconsistent results then
6430		 * we pretend that device does not exist.
6431		 */
6432		if (scsi_device_identity(sdprobe, SLEEP_FUNC)) {
6433			scsi_enumeration_failed(probe, -1, NULL, "identify");
6434			sp = SCSIPROBE_FAILURE;
6435		}
6436
6437		/*
6438		 * Future: Is there anything more we can do here to help avoid
6439		 * serialization on iport parent during scsi_device attach(9E)?
6440		 */
6441	}
6442	scsi_hba_devi_enter(self, circp);
6443	sdprobe->sd_uninit_prevent--;
6444
6445	if (sp != SCSIPROBE_EXISTS) {
6446		scsi_enumeration_failed(probe, -1, NULL, "probe");
6447
6448		if ((se != SE_HP) && scsi_hba_barrier_timeout) {
6449			/*
6450			 * Target does not exist. Mark the barrier probe node
6451			 * as DEVICE_REMOVED and schedule an asynchronous
6452			 * deletion of the node in scsi_hba_barrier_timeout
6453			 * seconds. We keep our hold on the probe node
6454			 * until we are ready perform the asynchronous node
6455			 * deletion.
6456			 */
6457			SCSI_HBA_LOG((_LOG(3), NULL, probe,
6458			    "set probe DEVICE_REMOVED"));
6459			mutex_enter(&DEVI(probe)->devi_lock);
6460			DEVI_SET_DEVICE_REMOVED(probe);
6461			mutex_exit(&DEVI(probe)->devi_lock);
6462
6463			scsi_hba_barrier_add(probe, scsi_hba_barrier_timeout);
6464			probe = NULL;
6465		}
6466		goto fail;
6467	}
6468
6469	/* Create the child node from the inquiry data in the probe node. */
6470	if ((child = scsi_device_configchild(self, addr, se, sdprobe,
6471	    circp, &pi)) == NULL) {
6472		/*
6473		 * This may fail because there was no driver binding identified
6474		 * via driver_alias. We may still have a conf node.
6475		 */
6476		if (name) {
6477			(void) scsi_findchild(self, name, addr,
6478			    0, &child, NULL, &pi);
6479			if (child)
6480				SCSI_HBA_LOG((_LOG(2), NULL, child,
6481				    "using driver.conf driver binding"));
6482		}
6483		if (child == NULL) {
6484			SCSI_HBA_LOG((_LOG(2), NULL, probe,
6485			    "device not configured"));
6486			goto fail;
6487		}
6488	}
6489
6490	/*
6491	 * Transfer the inquiry data from the probe node to the child
6492	 * SID node to avoid an extra scsi_probe. Callers depend on
6493	 * established inquiry data for the returned scsi_device.
6494	 */
6495	sdchild = ddi_get_driver_private(child);
6496	if (sdchild && (sdchild->sd_inq == NULL)) {
6497		sdchild->sd_inq = sdprobe->sd_inq;
6498		sdprobe->sd_inq = NULL;
6499	}
6500
6501	/*
6502	 * If we are doing a bus_configone and the node we created has the
6503	 * wrong node and driver name then switch the return result to a
6504	 * driver.conf node with the correct name - if such a node exists.
6505	 */
6506	if (name && (strcmp(ddi_node_name(child), name) != 0) &&
6507	    (strcmp(ddi_driver_name(child), name) != 0)) {
6508		(void) scsi_findchild(self, name, addr,
6509		    0, &dsearch, NULL, &pi);
6510		if (dsearch == NULL) {
6511			SCSI_HBA_LOG((_LOG(2), NULL, child,
6512			    "wrong device configured %s@%s", name, addr));
6513			/*
6514			 * We can't remove when modrootloaded == 0 in case
6515			 * boot-device a uses generic name and
6516			 * scsi_hba_nodename_compatible_get() returned a
6517			 * legacy binding-set driver oriented name.
6518			 */
6519			if (modrootloaded) {
6520				(void) scsi_hba_remove_node(child);
6521				child = NULL;
6522				goto fail;
6523			}
6524		} else {
6525			SCSI_HBA_LOG((_LOG(2), NULL, dsearch,
6526			    "device configured, but switching to driver.conf"));
6527			child = dsearch;
6528		}
6529	}
6530
6531	/* get the scsi_device structure from the node */
6532	SCSI_HBA_LOG((_LOG(3), NULL, child, "device configured"));
6533
6534	if (child) {
6535done:		ASSERT(child);
6536		sdchild = ddi_get_driver_private(child);
6537		ASSERT(sdchild);
6538
6539		/*
6540		 * We may have ended up here after promotion of a previously
6541		 * demoted node, where demotion deleted sd_inq data in
6542		 * scsi_busctl_uninitchild.  We redo the scsi_probe() to
6543		 * reestablish sd_inq.  We also want to redo the scsi_probe
6544		 * for devices are currently device_isremove in order to
6545		 * detect new device_insert.
6546		 */
6547		if ((sdchild->sd_inq == NULL) ||
6548		    ((pi == 0) && ndi_devi_device_isremoved(child))) {
6549
6550			/* hotplug_node can only be revived via hotplug. */
6551			if ((se == SE_HP) || !ndi_dev_is_hotplug_node(child)) {
6552				SCSI_HBA_LOG((_LOG(3), NULL, child,
6553				    "scsi_probe() demoted devinfo"));
6554
6555				sp = scsi_probe(sdchild, SLEEP_FUNC);
6556
6557				if (sp == SCSIPROBE_EXISTS) {
6558					ASSERT(sdchild->sd_inq);
6559
6560					/*
6561					 * Devinfo child exists and we are
6562					 * talking to the device, report
6563					 * reinsert and note if this was a
6564					 * new reinsert.
6565					 */
6566					chg = ndi_devi_device_insert(child);
6567					SCSI_HBA_LOG((_LOGCFG, NULL, child,
6568					    "devinfo %s@%s device_reinsert%s",
6569					    name ? name : "", addr,
65