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