xref: /titanic_51/usr/src/uts/common/os/devcfg.c (revision d8d810637042c2a73a269f125dee75e8ed1421d1)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/note.h>
27 #include <sys/t_lock.h>
28 #include <sys/cmn_err.h>
29 #include <sys/instance.h>
30 #include <sys/conf.h>
31 #include <sys/stat.h>
32 #include <sys/ddi.h>
33 #include <sys/hwconf.h>
34 #include <sys/sunddi.h>
35 #include <sys/sunndi.h>
36 #include <sys/ddi_impldefs.h>
37 #include <sys/ndi_impldefs.h>
38 #include <sys/modctl.h>
39 #include <sys/contract/device_impl.h>
40 #include <sys/dacf.h>
41 #include <sys/promif.h>
42 #include <sys/pci.h>
43 #include <sys/cpuvar.h>
44 #include <sys/pathname.h>
45 #include <sys/taskq.h>
46 #include <sys/sysevent.h>
47 #include <sys/sunmdi.h>
48 #include <sys/stream.h>
49 #include <sys/strsubr.h>
50 #include <sys/fs/snode.h>
51 #include <sys/fs/dv_node.h>
52 #include <sys/reboot.h>
53 #include <sys/sysmacros.h>
54 #include <sys/systm.h>
55 #include <sys/fs/sdev_impl.h>
56 #include <sys/sunldi.h>
57 #include <sys/sunldi_impl.h>
58 
59 #if defined(__i386) || defined(__amd64)
60 #if !defined(__xpv)
61 #include <sys/iommulib.h>
62 #endif
63 #endif
64 
65 #ifdef DEBUG
66 int ddidebug = DDI_AUDIT;
67 #else
68 int ddidebug = 0;
69 #endif
70 
71 #define	MT_CONFIG_OP	0
72 #define	MT_UNCONFIG_OP	1
73 
74 /* Multi-threaded configuration */
75 struct mt_config_handle {
76 	kmutex_t mtc_lock;
77 	kcondvar_t mtc_cv;
78 	int mtc_thr_count;
79 	dev_info_t *mtc_pdip;	/* parent dip for mt_config_children */
80 	dev_info_t **mtc_fdip;	/* "a" dip where unconfigure failed */
81 	major_t mtc_parmajor;	/* parent major for mt_config_driver */
82 	major_t mtc_major;
83 	int mtc_flags;
84 	int mtc_op;		/* config or unconfig */
85 	int mtc_error;		/* operation error */
86 	struct brevq_node **mtc_brevqp;	/* outstanding branch events queue */
87 #ifdef DEBUG
88 	int total_time;
89 	timestruc_t start_time;
90 #endif /* DEBUG */
91 };
92 
93 struct devi_nodeid {
94 	pnode_t nodeid;
95 	dev_info_t *dip;
96 	struct devi_nodeid *next;
97 };
98 
99 struct devi_nodeid_list {
100 	kmutex_t dno_lock;		/* Protects other fields */
101 	struct devi_nodeid *dno_head;	/* list of devi nodeid elements */
102 	struct devi_nodeid *dno_free;	/* Free list */
103 	uint_t dno_list_length;		/* number of dips in list */
104 };
105 
106 /* used to keep track of branch remove events to be generated */
107 struct brevq_node {
108 	char *brn_deviname;
109 	struct brevq_node *brn_sibling;
110 	struct brevq_node *brn_child;
111 };
112 
113 static struct devi_nodeid_list devi_nodeid_list;
114 static struct devi_nodeid_list *devimap = &devi_nodeid_list;
115 
116 /*
117  * Well known nodes which are attached first at boot time.
118  */
119 dev_info_t *top_devinfo;		/* root of device tree */
120 dev_info_t *options_dip;
121 dev_info_t *pseudo_dip;
122 dev_info_t *clone_dip;
123 dev_info_t *scsi_vhci_dip;		/* MPXIO dip */
124 major_t clone_major;
125 
126 /*
127  * A non-global zone's /dev is derived from the device tree.
128  * This generation number serves to indicate when a zone's
129  * /dev may need to be updated.
130  */
131 volatile ulong_t devtree_gen;		/* generation number */
132 
133 /* block all future dev_info state changes */
134 hrtime_t volatile devinfo_freeze = 0;
135 
136 /* number of dev_info attaches/detaches currently in progress */
137 static ulong_t devinfo_attach_detach = 0;
138 
139 extern int	sys_shutdown;
140 extern kmutex_t global_vhci_lock;
141 
142 /* bitset of DS_SYSAVAIL & DS_RECONFIG - no races, no lock */
143 static int devname_state = 0;
144 
145 /*
146  * The devinfo snapshot cache and related variables.
147  * The only field in the di_cache structure that needs initialization
148  * is the mutex (cache_lock). However, since this is an adaptive mutex
149  * (MUTEX_DEFAULT) - it is automatically initialized by being allocated
150  * in zeroed memory (static storage class). Therefore no explicit
151  * initialization of the di_cache structure is needed.
152  */
153 struct di_cache	di_cache = {1};
154 int		di_cache_debug = 0;
155 
156 /* For ddvis, which needs pseudo children under PCI */
157 int pci_allow_pseudo_children = 0;
158 
159 /* Allow path-oriented alias driver binding on driver.conf enumerated nodes */
160 int driver_conf_allow_path_alias = 1;
161 
162 /*
163  * The following switch is for service people, in case a
164  * 3rd party driver depends on identify(9e) being called.
165  */
166 int identify_9e = 0;
167 
168 int mtc_off;					/* turn off mt config */
169 
170 int quiesce_debug = 0;
171 
172 static kmem_cache_t *ddi_node_cache;		/* devinfo node cache */
173 static devinfo_log_header_t *devinfo_audit_log;	/* devinfo log */
174 static int devinfo_log_size;			/* size in pages */
175 
176 static int lookup_compatible(dev_info_t *, uint_t);
177 static char *encode_composite_string(char **, uint_t, size_t *, uint_t);
178 static void link_to_driver_list(dev_info_t *);
179 static void unlink_from_driver_list(dev_info_t *);
180 static void add_to_dn_list(struct devnames *, dev_info_t *);
181 static void remove_from_dn_list(struct devnames *, dev_info_t *);
182 static dev_info_t *find_duplicate_child();
183 static void add_global_props(dev_info_t *);
184 static void remove_global_props(dev_info_t *);
185 static int uninit_node(dev_info_t *);
186 static void da_log_init(void);
187 static void da_log_enter(dev_info_t *);
188 static int walk_devs(dev_info_t *, int (*f)(dev_info_t *, void *), void *, int);
189 static int reset_nexus_flags(dev_info_t *, void *);
190 static void ddi_optimize_dtree(dev_info_t *);
191 static int is_leaf_node(dev_info_t *);
192 static struct mt_config_handle *mt_config_init(dev_info_t *, dev_info_t **,
193     int, major_t, int, struct brevq_node **);
194 static void mt_config_children(struct mt_config_handle *);
195 static void mt_config_driver(struct mt_config_handle *);
196 static int mt_config_fini(struct mt_config_handle *);
197 static int devi_unconfig_common(dev_info_t *, dev_info_t **, int, major_t,
198     struct brevq_node **);
199 static int
200 ndi_devi_config_obp_args(dev_info_t *parent, char *devnm,
201     dev_info_t **childp, int flags);
202 static void i_link_vhci_node(dev_info_t *);
203 static void ndi_devi_exit_and_wait(dev_info_t *dip,
204     int circular, clock_t end_time);
205 static int ndi_devi_unbind_driver(dev_info_t *dip);
206 
207 static void i_ddi_check_retire(dev_info_t *dip);
208 
209 static void quiesce_one_device(dev_info_t *, void *);
210 
211 /*
212  * dev_info cache and node management
213  */
214 
215 /* initialize dev_info node cache */
216 void
217 i_ddi_node_cache_init()
218 {
219 	ASSERT(ddi_node_cache == NULL);
220 	ddi_node_cache = kmem_cache_create("dev_info_node_cache",
221 	    sizeof (struct dev_info), 0, NULL, NULL, NULL, NULL, NULL, 0);
222 
223 	if (ddidebug & DDI_AUDIT)
224 		da_log_init();
225 }
226 
227 /*
228  * Allocating a dev_info node, callable from interrupt context with KM_NOSLEEP
229  * The allocated node has a reference count of 0.
230  */
231 dev_info_t *
232 i_ddi_alloc_node(dev_info_t *pdip, char *node_name, pnode_t nodeid,
233     int instance, ddi_prop_t *sys_prop, int flag)
234 {
235 	struct dev_info *devi;
236 	struct devi_nodeid *elem;
237 	static char failed[] = "i_ddi_alloc_node: out of memory";
238 
239 	ASSERT(node_name != NULL);
240 
241 	if ((devi = kmem_cache_alloc(ddi_node_cache, flag)) == NULL) {
242 		cmn_err(CE_NOTE, failed);
243 		return (NULL);
244 	}
245 
246 	bzero(devi, sizeof (struct dev_info));
247 
248 	if (devinfo_audit_log) {
249 		devi->devi_audit = kmem_zalloc(sizeof (devinfo_audit_t), flag);
250 		if (devi->devi_audit == NULL)
251 			goto fail;
252 	}
253 
254 	if ((devi->devi_node_name = i_ddi_strdup(node_name, flag)) == NULL)
255 		goto fail;
256 
257 	/* default binding name is node name */
258 	devi->devi_binding_name = devi->devi_node_name;
259 	devi->devi_major = DDI_MAJOR_T_NONE;	/* unbound by default */
260 
261 	/*
262 	 * Make a copy of system property
263 	 */
264 	if (sys_prop &&
265 	    (devi->devi_sys_prop_ptr = i_ddi_prop_list_dup(sys_prop, flag))
266 	    == NULL)
267 		goto fail;
268 
269 	/*
270 	 * Assign devi_nodeid, devi_node_class, devi_node_attributes
271 	 * according to the following algorithm:
272 	 *
273 	 * nodeid arg			node class		node attributes
274 	 *
275 	 * DEVI_PSEUDO_NODEID		DDI_NC_PSEUDO		A
276 	 * DEVI_SID_NODEID		DDI_NC_PSEUDO		A,P
277 	 * DEVI_SID_HIDDEN_NODEID	DDI_NC_PSEUDO		A,P,H
278 	 * DEVI_SID_HP_NODEID		DDI_NC_PSEUDO		A,P,h
279 	 * DEVI_SID_HP_HIDDEN_NODEID	DDI_NC_PSEUDO		A,P,H,h
280 	 * other			DDI_NC_PROM		P
281 	 *
282 	 * Where A = DDI_AUTO_ASSIGNED_NODEID (auto-assign a nodeid)
283 	 * and	 P = DDI_PERSISTENT
284 	 * and	 H = DDI_HIDDEN_NODE
285 	 * and	 h = DDI_HOTPLUG_NODE
286 	 *
287 	 * auto-assigned nodeids are also auto-freed.
288 	 */
289 	devi->devi_node_attributes = 0;
290 	switch (nodeid) {
291 	case DEVI_SID_HIDDEN_NODEID:
292 		devi->devi_node_attributes |= DDI_HIDDEN_NODE;
293 		goto sid;
294 
295 	case DEVI_SID_HP_NODEID:
296 		devi->devi_node_attributes |= DDI_HOTPLUG_NODE;
297 		goto sid;
298 
299 	case DEVI_SID_HP_HIDDEN_NODEID:
300 		devi->devi_node_attributes |= DDI_HIDDEN_NODE;
301 		devi->devi_node_attributes |= DDI_HOTPLUG_NODE;
302 		goto sid;
303 
304 	case DEVI_SID_NODEID:
305 sid:		devi->devi_node_attributes |= DDI_PERSISTENT;
306 		if ((elem = kmem_zalloc(sizeof (*elem), flag)) == NULL)
307 			goto fail;
308 		/*FALLTHROUGH*/
309 
310 	case DEVI_PSEUDO_NODEID:
311 		devi->devi_node_attributes |= DDI_AUTO_ASSIGNED_NODEID;
312 		devi->devi_node_class = DDI_NC_PSEUDO;
313 		if (impl_ddi_alloc_nodeid(&devi->devi_nodeid)) {
314 			panic("i_ddi_alloc_node: out of nodeids");
315 			/*NOTREACHED*/
316 		}
317 		break;
318 
319 	default:
320 		if ((elem = kmem_zalloc(sizeof (*elem), flag)) == NULL)
321 			goto fail;
322 
323 		/*
324 		 * the nodetype is 'prom', try to 'take' the nodeid now.
325 		 * This requires memory allocation, so check for failure.
326 		 */
327 		if (impl_ddi_take_nodeid(nodeid, flag) != 0) {
328 			kmem_free(elem, sizeof (*elem));
329 			goto fail;
330 		}
331 
332 		devi->devi_nodeid = nodeid;
333 		devi->devi_node_class = DDI_NC_PROM;
334 		devi->devi_node_attributes = DDI_PERSISTENT;
335 		break;
336 	}
337 
338 	if (ndi_dev_is_persistent_node((dev_info_t *)devi)) {
339 		mutex_enter(&devimap->dno_lock);
340 		elem->next = devimap->dno_free;
341 		devimap->dno_free = elem;
342 		mutex_exit(&devimap->dno_lock);
343 	}
344 
345 	/*
346 	 * Instance is normally initialized to -1. In a few special
347 	 * cases, the caller may specify an instance (e.g. CPU nodes).
348 	 */
349 	devi->devi_instance = instance;
350 
351 	/*
352 	 * set parent and bus_ctl parent
353 	 */
354 	devi->devi_parent = DEVI(pdip);
355 	devi->devi_bus_ctl = DEVI(pdip);
356 
357 	NDI_CONFIG_DEBUG((CE_CONT,
358 	    "i_ddi_alloc_node: name=%s id=%d\n", node_name, devi->devi_nodeid));
359 
360 	cv_init(&(devi->devi_cv), NULL, CV_DEFAULT, NULL);
361 	mutex_init(&(devi->devi_lock), NULL, MUTEX_DEFAULT, NULL);
362 	mutex_init(&(devi->devi_pm_lock), NULL, MUTEX_DEFAULT, NULL);
363 	mutex_init(&(devi->devi_pm_busy_lock), NULL, MUTEX_DEFAULT, NULL);
364 
365 	RIO_TRACE((CE_NOTE, "i_ddi_alloc_node: Initing contract fields: "
366 	    "dip=%p, name=%s", (void *)devi, node_name));
367 
368 	mutex_init(&(devi->devi_ct_lock), NULL, MUTEX_DEFAULT, NULL);
369 	cv_init(&(devi->devi_ct_cv), NULL, CV_DEFAULT, NULL);
370 	devi->devi_ct_count = -1;	/* counter not in use if -1 */
371 	list_create(&(devi->devi_ct), sizeof (cont_device_t),
372 	    offsetof(cont_device_t, cond_next));
373 
374 	i_ddi_set_node_state((dev_info_t *)devi, DS_PROTO);
375 	da_log_enter((dev_info_t *)devi);
376 	return ((dev_info_t *)devi);
377 
378 fail:
379 	if (devi->devi_sys_prop_ptr)
380 		i_ddi_prop_list_delete(devi->devi_sys_prop_ptr);
381 	if (devi->devi_node_name)
382 		kmem_free(devi->devi_node_name, strlen(node_name) + 1);
383 	if (devi->devi_audit)
384 		kmem_free(devi->devi_audit, sizeof (devinfo_audit_t));
385 	kmem_cache_free(ddi_node_cache, devi);
386 	cmn_err(CE_NOTE, failed);
387 	return (NULL);
388 }
389 
390 /*
391  * free a dev_info structure.
392  * NB. Not callable from interrupt since impl_ddi_free_nodeid may block.
393  */
394 void
395 i_ddi_free_node(dev_info_t *dip)
396 {
397 	struct dev_info *devi = DEVI(dip);
398 	struct devi_nodeid *elem;
399 #if defined(__x86) && !defined(__xpv)
400 	gfx_entry_t *gfxp;
401 	extern void *gfx_devinfo_list;
402 #endif
403 
404 	ASSERT(devi->devi_ref == 0);
405 	ASSERT(devi->devi_addr == NULL);
406 	ASSERT(devi->devi_node_state == DS_PROTO);
407 	ASSERT(devi->devi_child == NULL);
408 
409 #if defined(__x86) && !defined(__xpv)
410 	for (gfxp = gfx_devinfo_list; gfxp; gfxp = gfxp->g_next) {
411 		if (gfxp->g_dip == dip) {
412 			gfxp->g_dip = NULL;
413 			while (gfxp->g_ref)
414 				;
415 		}
416 	}
417 	membar_producer();
418 #endif
419 	/* free devi_addr_buf allocated by ddi_set_name_addr() */
420 	if (devi->devi_addr_buf)
421 		kmem_free(devi->devi_addr_buf, 2 * MAXNAMELEN);
422 
423 	if (i_ndi_dev_is_auto_assigned_node(dip))
424 		impl_ddi_free_nodeid(DEVI(dip)->devi_nodeid);
425 
426 	if (ndi_dev_is_persistent_node(dip)) {
427 		mutex_enter(&devimap->dno_lock);
428 		ASSERT(devimap->dno_free);
429 		elem = devimap->dno_free;
430 		devimap->dno_free = elem->next;
431 		mutex_exit(&devimap->dno_lock);
432 		kmem_free(elem, sizeof (*elem));
433 	}
434 
435 	if (DEVI(dip)->devi_compat_names)
436 		kmem_free(DEVI(dip)->devi_compat_names,
437 		    DEVI(dip)->devi_compat_length);
438 	if (DEVI(dip)->devi_rebinding_name)
439 		kmem_free(DEVI(dip)->devi_rebinding_name,
440 		    strlen(DEVI(dip)->devi_rebinding_name) + 1);
441 
442 	ddi_prop_remove_all(dip);	/* remove driver properties */
443 	if (devi->devi_sys_prop_ptr)
444 		i_ddi_prop_list_delete(devi->devi_sys_prop_ptr);
445 	if (devi->devi_hw_prop_ptr)
446 		i_ddi_prop_list_delete(devi->devi_hw_prop_ptr);
447 
448 	if (DEVI(dip)->devi_devid_str)
449 		ddi_devid_str_free(DEVI(dip)->devi_devid_str);
450 
451 	i_ddi_set_node_state(dip, DS_INVAL);
452 	da_log_enter(dip);
453 	if (devi->devi_audit) {
454 		kmem_free(devi->devi_audit, sizeof (devinfo_audit_t));
455 	}
456 	if (devi->devi_device_class)
457 		kmem_free(devi->devi_device_class,
458 		    strlen(devi->devi_device_class) + 1);
459 	cv_destroy(&(devi->devi_cv));
460 	mutex_destroy(&(devi->devi_lock));
461 	mutex_destroy(&(devi->devi_pm_lock));
462 	mutex_destroy(&(devi->devi_pm_busy_lock));
463 
464 	RIO_TRACE((CE_NOTE, "i_ddi_free_node: destroying contract fields: "
465 	    "dip=%p", (void *)dip));
466 	contract_device_remove_dip(dip);
467 	ASSERT(devi->devi_ct_count == -1);
468 	ASSERT(list_is_empty(&(devi->devi_ct)));
469 	cv_destroy(&(devi->devi_ct_cv));
470 	list_destroy(&(devi->devi_ct));
471 	/* free this last since contract_device_remove_dip() uses it */
472 	mutex_destroy(&(devi->devi_ct_lock));
473 	RIO_TRACE((CE_NOTE, "i_ddi_free_node: destroyed all contract fields: "
474 	    "dip=%p, name=%s", (void *)dip, devi->devi_node_name));
475 
476 	kmem_free(devi->devi_node_name, strlen(devi->devi_node_name) + 1);
477 
478 	kmem_cache_free(ddi_node_cache, devi);
479 }
480 
481 
482 /*
483  * Node state transitions
484  */
485 
486 /*
487  * Change the node name
488  */
489 int
490 ndi_devi_set_nodename(dev_info_t *dip, char *name, int flags)
491 {
492 	_NOTE(ARGUNUSED(flags))
493 	char *nname, *oname;
494 
495 	ASSERT(dip && name);
496 
497 	oname = DEVI(dip)->devi_node_name;
498 	if (strcmp(oname, name) == 0)
499 		return (DDI_SUCCESS);
500 
501 	/*
502 	 * pcicfg_fix_ethernet requires a name change after node
503 	 * is linked into the tree. When pcicfg is fixed, we
504 	 * should only allow name change in DS_PROTO state.
505 	 */
506 	if (i_ddi_node_state(dip) >= DS_BOUND) {
507 		/*
508 		 * Don't allow name change once node is bound
509 		 */
510 		cmn_err(CE_NOTE,
511 		    "ndi_devi_set_nodename: node already bound dip = %p,"
512 		    " %s -> %s", (void *)dip, ddi_node_name(dip), name);
513 		return (NDI_FAILURE);
514 	}
515 
516 	nname = i_ddi_strdup(name, KM_SLEEP);
517 	DEVI(dip)->devi_node_name = nname;
518 	i_ddi_set_binding_name(dip, nname);
519 	kmem_free(oname, strlen(oname) + 1);
520 
521 	da_log_enter(dip);
522 	return (NDI_SUCCESS);
523 }
524 
525 void
526 i_ddi_add_devimap(dev_info_t *dip)
527 {
528 	struct devi_nodeid *elem;
529 
530 	ASSERT(dip);
531 
532 	if (!ndi_dev_is_persistent_node(dip))
533 		return;
534 
535 	ASSERT(ddi_get_parent(dip) == NULL || (DEVI_VHCI_NODE(dip)) ||
536 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
537 
538 	mutex_enter(&devimap->dno_lock);
539 
540 	ASSERT(devimap->dno_free);
541 
542 	elem = devimap->dno_free;
543 	devimap->dno_free = elem->next;
544 
545 	elem->nodeid = ddi_get_nodeid(dip);
546 	elem->dip = dip;
547 	elem->next = devimap->dno_head;
548 	devimap->dno_head = elem;
549 
550 	devimap->dno_list_length++;
551 
552 	mutex_exit(&devimap->dno_lock);
553 }
554 
555 static int
556 i_ddi_remove_devimap(dev_info_t *dip)
557 {
558 	struct devi_nodeid *prev, *elem;
559 	static const char *fcn = "i_ddi_remove_devimap";
560 
561 	ASSERT(dip);
562 
563 	if (!ndi_dev_is_persistent_node(dip))
564 		return (DDI_SUCCESS);
565 
566 	mutex_enter(&devimap->dno_lock);
567 
568 	/*
569 	 * The following check is done with dno_lock held
570 	 * to prevent race between dip removal and
571 	 * e_ddi_prom_node_to_dip()
572 	 */
573 	if (e_ddi_devi_holdcnt(dip)) {
574 		mutex_exit(&devimap->dno_lock);
575 		return (DDI_FAILURE);
576 	}
577 
578 	ASSERT(devimap->dno_head);
579 	ASSERT(devimap->dno_list_length > 0);
580 
581 	prev = NULL;
582 	for (elem = devimap->dno_head; elem; elem = elem->next) {
583 		if (elem->dip == dip) {
584 			ASSERT(elem->nodeid == ddi_get_nodeid(dip));
585 			break;
586 		}
587 		prev = elem;
588 	}
589 
590 	if (elem && prev)
591 		prev->next = elem->next;
592 	else if (elem)
593 		devimap->dno_head = elem->next;
594 	else
595 		panic("%s: devinfo node(%p) not found",
596 		    fcn, (void *)dip);
597 
598 	devimap->dno_list_length--;
599 
600 	elem->nodeid = 0;
601 	elem->dip = NULL;
602 
603 	elem->next = devimap->dno_free;
604 	devimap->dno_free = elem;
605 
606 	mutex_exit(&devimap->dno_lock);
607 
608 	return (DDI_SUCCESS);
609 }
610 
611 /*
612  * Link this node into the devinfo tree and add to orphan list
613  * Not callable from interrupt context
614  */
615 static void
616 link_node(dev_info_t *dip)
617 {
618 	struct dev_info *devi = DEVI(dip);
619 	struct dev_info *parent = devi->devi_parent;
620 	dev_info_t **dipp;
621 
622 	ASSERT(parent);	/* never called for root node */
623 
624 	NDI_CONFIG_DEBUG((CE_CONT, "link_node: parent = %s child = %s\n",
625 	    parent->devi_node_name, devi->devi_node_name));
626 
627 	/*
628 	 * Hold the global_vhci_lock before linking any direct
629 	 * children of rootnex driver. This special lock protects
630 	 * linking and unlinking for rootnext direct children.
631 	 */
632 	if ((dev_info_t *)parent == ddi_root_node())
633 		mutex_enter(&global_vhci_lock);
634 
635 	/*
636 	 * attach the node to end of the list unless the node is already there
637 	 */
638 	dipp = (dev_info_t **)(&DEVI(parent)->devi_child);
639 	while (*dipp && (*dipp != dip)) {
640 		dipp = (dev_info_t **)(&DEVI(*dipp)->devi_sibling);
641 	}
642 	ASSERT(*dipp == NULL);	/* node is not linked */
643 
644 	/*
645 	 * Now that we are in the tree, update the devi-nodeid map.
646 	 */
647 	i_ddi_add_devimap(dip);
648 
649 	/*
650 	 * This is a temporary workaround for Bug 4618861.
651 	 * We keep the scsi_vhci nexus node on the left side of the devinfo
652 	 * tree (under the root nexus driver), so that virtual nodes under
653 	 * scsi_vhci will be SUSPENDed first and RESUMEd last.  This ensures
654 	 * that the pHCI nodes are active during times when their clients
655 	 * may be depending on them.  This workaround embodies the knowledge
656 	 * that system PM and CPR both traverse the tree left-to-right during
657 	 * SUSPEND and right-to-left during RESUME.
658 	 * Extending the workaround to IB Nexus/VHCI
659 	 * driver also.
660 	 */
661 	if (strcmp(devi->devi_binding_name, "scsi_vhci") == 0) {
662 		/* Add scsi_vhci to beginning of list */
663 		ASSERT((dev_info_t *)parent == top_devinfo);
664 		/* scsi_vhci under rootnex */
665 		devi->devi_sibling = parent->devi_child;
666 		parent->devi_child = devi;
667 	} else if (strcmp(devi->devi_binding_name, "ib") == 0) {
668 		i_link_vhci_node(dip);
669 	} else {
670 		/* Add to end of list */
671 		*dipp = dip;
672 		DEVI(dip)->devi_sibling = NULL;
673 	}
674 
675 	/*
676 	 * Release the global_vhci_lock before linking any direct
677 	 * children of rootnex driver.
678 	 */
679 	if ((dev_info_t *)parent == ddi_root_node())
680 		mutex_exit(&global_vhci_lock);
681 
682 	/* persistent nodes go on orphan list */
683 	if (ndi_dev_is_persistent_node(dip))
684 		add_to_dn_list(&orphanlist, dip);
685 }
686 
687 /*
688  * Unlink this node from the devinfo tree
689  */
690 static int
691 unlink_node(dev_info_t *dip)
692 {
693 	struct dev_info *devi = DEVI(dip);
694 	struct dev_info *parent = devi->devi_parent;
695 	dev_info_t **dipp;
696 
697 	ASSERT(parent != NULL);
698 	ASSERT(devi->devi_node_state == DS_LINKED);
699 
700 	NDI_CONFIG_DEBUG((CE_CONT, "unlink_node: name = %s\n",
701 	    ddi_node_name(dip)));
702 
703 	/* check references */
704 	if (devi->devi_ref || i_ddi_remove_devimap(dip) != DDI_SUCCESS)
705 		return (DDI_FAILURE);
706 
707 	/*
708 	 * Hold the global_vhci_lock before linking any direct
709 	 * children of rootnex driver.
710 	 */
711 	if ((dev_info_t *)parent == ddi_root_node())
712 		mutex_enter(&global_vhci_lock);
713 
714 	dipp = (dev_info_t **)(&DEVI(parent)->devi_child);
715 	while (*dipp && (*dipp != dip)) {
716 		dipp = (dev_info_t **)(&DEVI(*dipp)->devi_sibling);
717 	}
718 	if (*dipp) {
719 		*dipp = (dev_info_t *)(devi->devi_sibling);
720 		devi->devi_sibling = NULL;
721 	} else {
722 		NDI_CONFIG_DEBUG((CE_NOTE, "unlink_node: %s not linked",
723 		    devi->devi_node_name));
724 	}
725 
726 	/*
727 	 * Release the global_vhci_lock before linking any direct
728 	 * children of rootnex driver.
729 	 */
730 	if ((dev_info_t *)parent == ddi_root_node())
731 		mutex_exit(&global_vhci_lock);
732 
733 	/* Remove node from orphan list */
734 	if (ndi_dev_is_persistent_node(dip)) {
735 		remove_from_dn_list(&orphanlist, dip);
736 	}
737 
738 	return (DDI_SUCCESS);
739 }
740 
741 /*
742  * Bind this devinfo node to a driver. If compat is NON-NULL, try that first.
743  * Else, use the node-name.
744  *
745  * NOTE: IEEE1275 specifies that nodename should be tried before compatible.
746  *	Solaris implementation binds nodename after compatible.
747  *
748  * If we find a binding,
749  * - set the binding name to the string,
750  * - set major number to driver major
751  *
752  * If we don't find a binding,
753  * - return failure
754  */
755 static int
756 bind_node(dev_info_t *dip)
757 {
758 	char *p = NULL;
759 	major_t major = DDI_MAJOR_T_NONE;
760 	struct dev_info *devi = DEVI(dip);
761 	dev_info_t *parent = ddi_get_parent(dip);
762 
763 	ASSERT(devi->devi_node_state == DS_LINKED);
764 
765 	NDI_CONFIG_DEBUG((CE_CONT, "bind_node: 0x%p(name = %s)\n",
766 	    (void *)dip, ddi_node_name(dip)));
767 
768 	mutex_enter(&DEVI(dip)->devi_lock);
769 	if (DEVI(dip)->devi_flags & DEVI_NO_BIND) {
770 		mutex_exit(&DEVI(dip)->devi_lock);
771 		return (DDI_FAILURE);
772 	}
773 	mutex_exit(&DEVI(dip)->devi_lock);
774 
775 	/* find the driver with most specific binding using compatible */
776 	major = ddi_compatible_driver_major(dip, &p);
777 	if (major == DDI_MAJOR_T_NONE)
778 		return (DDI_FAILURE);
779 
780 	devi->devi_major = major;
781 	if (p != NULL) {
782 		i_ddi_set_binding_name(dip, p);
783 		NDI_CONFIG_DEBUG((CE_CONT, "bind_node: %s bound to %s\n",
784 		    devi->devi_node_name, p));
785 	}
786 
787 	/* Link node to per-driver list */
788 	link_to_driver_list(dip);
789 
790 	/*
791 	 * reset parent flag so that nexus will merge .conf props
792 	 */
793 	if (ndi_dev_is_persistent_node(dip)) {
794 		mutex_enter(&DEVI(parent)->devi_lock);
795 		DEVI(parent)->devi_flags &=
796 		    ~(DEVI_ATTACHED_CHILDREN|DEVI_MADE_CHILDREN);
797 		mutex_exit(&DEVI(parent)->devi_lock);
798 	}
799 	return (DDI_SUCCESS);
800 }
801 
802 /*
803  * Unbind this devinfo node
804  * Called before the node is destroyed or driver is removed from system
805  */
806 static int
807 unbind_node(dev_info_t *dip)
808 {
809 	ASSERT(DEVI(dip)->devi_node_state == DS_BOUND);
810 	ASSERT(DEVI(dip)->devi_major != DDI_MAJOR_T_NONE);
811 
812 	/* check references */
813 	if (DEVI(dip)->devi_ref)
814 		return (DDI_FAILURE);
815 
816 	NDI_CONFIG_DEBUG((CE_CONT, "unbind_node: 0x%p(name = %s)\n",
817 	    (void *)dip, ddi_node_name(dip)));
818 
819 	unlink_from_driver_list(dip);
820 
821 	DEVI(dip)->devi_major = DDI_MAJOR_T_NONE;
822 	DEVI(dip)->devi_binding_name = DEVI(dip)->devi_node_name;
823 	return (DDI_SUCCESS);
824 }
825 
826 /*
827  * Initialize a node: calls the parent nexus' bus_ctl ops to do the operation.
828  * Must hold parent and per-driver list while calling this function.
829  * A successful init_node() returns with an active ndi_hold_devi() hold on
830  * the parent.
831  */
832 static int
833 init_node(dev_info_t *dip)
834 {
835 	int error;
836 	dev_info_t *pdip = ddi_get_parent(dip);
837 	int (*f)(dev_info_t *, dev_info_t *, ddi_ctl_enum_t, void *, void *);
838 	char *path;
839 	major_t	major;
840 
841 	ASSERT(i_ddi_node_state(dip) == DS_BOUND);
842 
843 	/* should be DS_READY except for pcmcia ... */
844 	ASSERT(i_ddi_node_state(pdip) >= DS_PROBED);
845 
846 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
847 	(void) ddi_pathname(dip, path);
848 	NDI_CONFIG_DEBUG((CE_CONT, "init_node: entry: path %s 0x%p\n",
849 	    path, (void *)dip));
850 
851 	/*
852 	 * The parent must have a bus_ctl operation.
853 	 */
854 	if ((DEVI(pdip)->devi_ops->devo_bus_ops == NULL) ||
855 	    (f = DEVI(pdip)->devi_ops->devo_bus_ops->bus_ctl) == NULL) {
856 		error = DDI_FAILURE;
857 		goto out;
858 	}
859 
860 	add_global_props(dip);
861 
862 	/*
863 	 * Invoke the parent's bus_ctl operation with the DDI_CTLOPS_INITCHILD
864 	 * command to transform the child to canonical form 1. If there
865 	 * is an error, ddi_remove_child should be called, to clean up.
866 	 */
867 	error = (*f)(pdip, pdip, DDI_CTLOPS_INITCHILD, dip, NULL);
868 	if (error != DDI_SUCCESS) {
869 		NDI_CONFIG_DEBUG((CE_CONT, "init_node: %s 0x%p failed\n",
870 		    path, (void *)dip));
871 		remove_global_props(dip);
872 		/* in case nexus driver didn't clear this field */
873 		ddi_set_name_addr(dip, NULL);
874 		error = DDI_FAILURE;
875 		goto out;
876 	}
877 
878 	ndi_hold_devi(pdip);			/* initial hold of parent */
879 
880 	/* recompute path after initchild for @addr information */
881 	(void) ddi_pathname(dip, path);
882 
883 	/* Check for duplicate nodes */
884 	if (find_duplicate_child(pdip, dip) != NULL) {
885 		/*
886 		 * uninit_node() the duplicate - a successful uninit_node()
887 		 * will release inital hold of parent using ndi_rele_devi().
888 		 */
889 		if ((error = uninit_node(dip)) != DDI_SUCCESS) {
890 			ndi_rele_devi(pdip);	/* release initial hold */
891 			cmn_err(CE_WARN, "init_node: uninit of duplicate "
892 			    "node %s failed", path);
893 		}
894 		NDI_CONFIG_DEBUG((CE_CONT, "init_node: duplicate uninit "
895 		    "%s 0x%p%s\n", path, (void *)dip,
896 		    (error == DDI_SUCCESS) ? "" : " failed"));
897 		error = DDI_FAILURE;
898 		goto out;
899 	}
900 
901 	/*
902 	 * Check to see if we have a path-oriented driver alias that overrides
903 	 * the current driver binding. If so, we need to rebind. This check
904 	 * needs to be delayed until after a successful DDI_CTLOPS_INITCHILD,
905 	 * so the unit-address is established on the last component of the path.
906 	 *
907 	 * NOTE: Allowing a path-oriented alias to change the driver binding
908 	 * of a driver.conf node results in non-intuitive property behavior.
909 	 * We provide a tunable (driver_conf_allow_path_alias) to control
910 	 * this behavior. See uninit_node() for more details.
911 	 *
912 	 * NOTE: If you are adding a path-oriented alias for the boot device,
913 	 * and there is mismatch between OBP and the kernel in regard to
914 	 * generic name use, like "disk" .vs. "ssd", then you will need
915 	 * to add a path-oriented alias for both paths.
916 	 */
917 	major = ddi_name_to_major(path);
918 	if ((major != DDI_MAJOR_T_NONE) &&
919 	    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED) &&
920 	    (major != DEVI(dip)->devi_major) &&
921 	    (ndi_dev_is_persistent_node(dip) || driver_conf_allow_path_alias)) {
922 
923 		/* Mark node for rebind processing. */
924 		mutex_enter(&DEVI(dip)->devi_lock);
925 		DEVI(dip)->devi_flags |= DEVI_REBIND;
926 		mutex_exit(&DEVI(dip)->devi_lock);
927 
928 		/*
929 		 * Add an extra hold on the parent to prevent it from ever
930 		 * having a zero devi_ref during the child rebind process.
931 		 * This is necessary to ensure that the parent will never
932 		 * detach(9E) during the rebind.
933 		 */
934 		ndi_hold_devi(pdip);		/* extra hold of parent */
935 
936 		/*
937 		 * uninit_node() current binding - a successful uninit_node()
938 		 * will release extra hold of parent using ndi_rele_devi().
939 		 */
940 		if ((error = uninit_node(dip)) != DDI_SUCCESS) {
941 			ndi_rele_devi(pdip);	/* release extra hold */
942 			ndi_rele_devi(pdip);	/* release initial hold */
943 			cmn_err(CE_WARN, "init_node: uninit for rebind "
944 			    "of node %s failed", path);
945 			goto out;
946 		}
947 
948 		/* Unbind: demote the node back to DS_LINKED.  */
949 		if ((error = ndi_devi_unbind_driver(dip)) != DDI_SUCCESS) {
950 			ndi_rele_devi(pdip);	/* release initial hold */
951 			cmn_err(CE_WARN, "init_node: unbind for rebind "
952 			    "of node %s failed", path);
953 			goto out;
954 		}
955 
956 		/* establish rebinding name */
957 		if (DEVI(dip)->devi_rebinding_name == NULL)
958 			DEVI(dip)->devi_rebinding_name =
959 			    i_ddi_strdup(path, KM_SLEEP);
960 
961 		/*
962 		 * Now that we are demoted and marked for rebind, repromote.
963 		 * We need to do this in steps, instead of just calling
964 		 * ddi_initchild, so that we can redo the merge operation
965 		 * after we are rebound to the path-bound driver.
966 		 *
967 		 * Start by rebinding node to the path-bound driver.
968 		 */
969 		if ((error = ndi_devi_bind_driver(dip, 0)) != DDI_SUCCESS) {
970 			ndi_rele_devi(pdip);	/* release initial hold */
971 			cmn_err(CE_WARN, "init_node: rebind "
972 			    "of node %s failed", path);
973 			goto out;
974 		}
975 
976 		/*
977 		 * If the node is not a driver.conf node then merge
978 		 * driver.conf properties from new path-bound driver.conf.
979 		 */
980 		if (ndi_dev_is_persistent_node(dip))
981 			(void) i_ndi_make_spec_children(pdip, 0);
982 
983 		/*
984 		 * Now that we have taken care of merge, repromote back
985 		 * to DS_INITIALIZED.
986 		 */
987 		error = ddi_initchild(pdip, dip);
988 		NDI_CONFIG_DEBUG((CE_CONT, "init_node: rebind "
989 		    "%s 0x%p\n", path, (void *)dip));
990 
991 		/*
992 		 * Release our initial hold. If ddi_initchild() was
993 		 * successful then it will return with the active hold.
994 		 */
995 		ndi_rele_devi(pdip);
996 		goto out;
997 	}
998 
999 	/*
1000 	 * Apply multi-parent/deep-nexus optimization to the new node
1001 	 */
1002 	DEVI(dip)->devi_instance = e_ddi_assign_instance(dip);
1003 	ddi_optimize_dtree(dip);
1004 	error = DDI_SUCCESS;		/* return with active hold */
1005 
1006 out:	if (error != DDI_SUCCESS) {
1007 		/* On failure ensure that DEVI_REBIND is cleared */
1008 		mutex_enter(&DEVI(dip)->devi_lock);
1009 		DEVI(dip)->devi_flags &= ~DEVI_REBIND;
1010 		mutex_exit(&DEVI(dip)->devi_lock);
1011 	}
1012 	kmem_free(path, MAXPATHLEN);
1013 	return (error);
1014 }
1015 
1016 /*
1017  * Uninitialize node
1018  * The per-driver list must be held busy during the call.
1019  * A successful uninit_node() releases the init_node() hold on
1020  * the parent by calling ndi_rele_devi().
1021  */
1022 static int
1023 uninit_node(dev_info_t *dip)
1024 {
1025 	int node_state_entry;
1026 	dev_info_t *pdip;
1027 	struct dev_ops *ops;
1028 	int (*f)();
1029 	int error;
1030 	char *addr;
1031 
1032 	/*
1033 	 * Don't check for references here or else a ref-counted
1034 	 * dip cannot be downgraded by the framework.
1035 	 */
1036 	node_state_entry = i_ddi_node_state(dip);
1037 	ASSERT((node_state_entry == DS_BOUND) ||
1038 	    (node_state_entry == DS_INITIALIZED));
1039 	pdip = ddi_get_parent(dip);
1040 	ASSERT(pdip);
1041 
1042 	NDI_CONFIG_DEBUG((CE_CONT, "uninit_node: 0x%p(%s%d)\n",
1043 	    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1044 
1045 	if (((ops = ddi_get_driver(pdip)) == NULL) ||
1046 	    (ops->devo_bus_ops == NULL) ||
1047 	    ((f = ops->devo_bus_ops->bus_ctl) == NULL)) {
1048 		return (DDI_FAILURE);
1049 	}
1050 
1051 	/*
1052 	 * save the @addr prior to DDI_CTLOPS_UNINITCHILD for use in
1053 	 * freeing the instance if it succeeds.
1054 	 */
1055 	if (node_state_entry == DS_INITIALIZED) {
1056 		addr = ddi_get_name_addr(dip);
1057 		if (addr)
1058 			addr = i_ddi_strdup(addr, KM_SLEEP);
1059 	} else {
1060 		addr = NULL;
1061 	}
1062 
1063 	error = (*f)(pdip, pdip, DDI_CTLOPS_UNINITCHILD, dip, (void *)NULL);
1064 	if (error == DDI_SUCCESS) {
1065 		/* ensure that devids are unregistered */
1066 		if (DEVI(dip)->devi_flags & DEVI_REGISTERED_DEVID) {
1067 			DEVI(dip)->devi_flags &= ~DEVI_REGISTERED_DEVID;
1068 			ddi_devid_unregister(dip);
1069 		}
1070 
1071 		/* if uninitchild forgot to set devi_addr to NULL do it now */
1072 		ddi_set_name_addr(dip, NULL);
1073 
1074 		/*
1075 		 * Free instance number. This is a no-op if instance has
1076 		 * been kept by probe_node().  Avoid free when we are called
1077 		 * from init_node (DS_BOUND) because the instance has not yet
1078 		 * been assigned.
1079 		 */
1080 		if (node_state_entry == DS_INITIALIZED) {
1081 			e_ddi_free_instance(dip, addr);
1082 			DEVI(dip)->devi_instance = -1;
1083 		}
1084 
1085 		/* release the init_node hold */
1086 		ndi_rele_devi(pdip);
1087 
1088 		remove_global_props(dip);
1089 
1090 		/*
1091 		 * NOTE: The decision on whether to allow a path-oriented
1092 		 * rebind of a driver.conf enumerated node is made by
1093 		 * init_node() based on driver_conf_allow_path_alias. The
1094 		 * rebind code below prevents deletion of system properties
1095 		 * on driver.conf nodes.
1096 		 *
1097 		 * When driver_conf_allow_path_alias is set, property behavior
1098 		 * on rebound driver.conf file is non-intuitive. For a
1099 		 * driver.conf node, the unit-address properties come from
1100 		 * the driver.conf file as system properties. Removing system
1101 		 * properties from a driver.conf node makes the node
1102 		 * useless (we get node without unit-address properties) - so
1103 		 * we leave system properties in place. The result is a node
1104 		 * where system properties come from the node being rebound,
1105 		 * and global properties come from the driver.conf file
1106 		 * of the driver we are rebinding to.  If we could determine
1107 		 * that the path-oriented alias driver.conf file defined a
1108 		 * node at the same unit address, it would be best to use
1109 		 * that node and avoid the non-intuitive property behavior.
1110 		 * Unfortunately, the current "merge" code does not support
1111 		 * this, so we live with the non-intuitive property behavior.
1112 		 */
1113 		if (!((ndi_dev_is_persistent_node(dip) == 0) &&
1114 		    (DEVI(dip)->devi_flags & DEVI_REBIND)))
1115 			e_ddi_prop_remove_all(dip);
1116 	} else {
1117 		NDI_CONFIG_DEBUG((CE_CONT, "uninit_node failed: 0x%p(%s%d)\n",
1118 		    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1119 	}
1120 
1121 	if (addr)
1122 		kmem_free(addr, strlen(addr) + 1);
1123 	return (error);
1124 }
1125 
1126 /*
1127  * Invoke driver's probe entry point to probe for existence of hardware.
1128  * Keep instance permanent for successful probe and leaf nodes.
1129  *
1130  * Per-driver list must be held busy while calling this function.
1131  */
1132 static int
1133 probe_node(dev_info_t *dip)
1134 {
1135 	int rv;
1136 
1137 	ASSERT(i_ddi_node_state(dip) == DS_INITIALIZED);
1138 
1139 	NDI_CONFIG_DEBUG((CE_CONT, "probe_node: 0x%p(%s%d)\n",
1140 	    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1141 
1142 	/* temporarily hold the driver while we probe */
1143 	DEVI(dip)->devi_ops = ndi_hold_driver(dip);
1144 	if (DEVI(dip)->devi_ops == NULL) {
1145 		NDI_CONFIG_DEBUG((CE_CONT,
1146 		    "probe_node: 0x%p(%s%d) cannot load driver\n",
1147 		    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1148 		return (DDI_FAILURE);
1149 	}
1150 
1151 	if (identify_9e != 0)
1152 		(void) devi_identify(dip);
1153 
1154 	rv = devi_probe(dip);
1155 
1156 	/* release the driver now that probe is complete */
1157 	ndi_rele_driver(dip);
1158 	DEVI(dip)->devi_ops = NULL;
1159 
1160 	switch (rv) {
1161 	case DDI_PROBE_SUCCESS:			/* found */
1162 	case DDI_PROBE_DONTCARE:		/* ddi_dev_is_sid */
1163 		e_ddi_keep_instance(dip);	/* persist instance */
1164 		rv = DDI_SUCCESS;
1165 		break;
1166 
1167 	case DDI_PROBE_PARTIAL:			/* maybe later */
1168 	case DDI_PROBE_FAILURE:			/* not found */
1169 		NDI_CONFIG_DEBUG((CE_CONT,
1170 		    "probe_node: 0x%p(%s%d) no hardware found%s\n",
1171 		    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip),
1172 		    (rv == DDI_PROBE_PARTIAL) ? " yet" : ""));
1173 		rv = DDI_FAILURE;
1174 		break;
1175 
1176 	default:
1177 #ifdef	DEBUG
1178 		cmn_err(CE_WARN, "probe_node: %s%d: illegal probe(9E) value",
1179 		    ddi_driver_name(dip), ddi_get_instance(dip));
1180 #endif	/* DEBUG */
1181 		rv = DDI_FAILURE;
1182 		break;
1183 	}
1184 	return (rv);
1185 }
1186 
1187 /*
1188  * Unprobe a node. Simply reset the node state.
1189  * Per-driver list must be held busy while calling this function.
1190  */
1191 static int
1192 unprobe_node(dev_info_t *dip)
1193 {
1194 	ASSERT(i_ddi_node_state(dip) == DS_PROBED);
1195 
1196 	/*
1197 	 * Don't check for references here or else a ref-counted
1198 	 * dip cannot be downgraded by the framework.
1199 	 */
1200 
1201 	NDI_CONFIG_DEBUG((CE_CONT, "unprobe_node: 0x%p(name = %s)\n",
1202 	    (void *)dip, ddi_node_name(dip)));
1203 	return (DDI_SUCCESS);
1204 }
1205 
1206 /*
1207  * Attach devinfo node.
1208  * Per-driver list must be held busy.
1209  */
1210 static int
1211 attach_node(dev_info_t *dip)
1212 {
1213 	int rv;
1214 
1215 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
1216 	ASSERT(i_ddi_node_state(dip) == DS_PROBED);
1217 
1218 	NDI_CONFIG_DEBUG((CE_CONT, "attach_node: 0x%p(%s%d)\n",
1219 	    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1220 
1221 	/*
1222 	 * Tell mpxio framework that a node is about to online.
1223 	 */
1224 	if ((rv = mdi_devi_online(dip, 0)) != NDI_SUCCESS) {
1225 		return (DDI_FAILURE);
1226 	}
1227 
1228 	/* no recursive attachment */
1229 	ASSERT(DEVI(dip)->devi_ops == NULL);
1230 
1231 	/*
1232 	 * Hold driver the node is bound to.
1233 	 */
1234 	DEVI(dip)->devi_ops = ndi_hold_driver(dip);
1235 	if (DEVI(dip)->devi_ops == NULL) {
1236 		/*
1237 		 * We were able to load driver for probing, so we should
1238 		 * not get here unless something really bad happened.
1239 		 */
1240 		cmn_err(CE_WARN, "attach_node: no driver for major %d",
1241 		    DEVI(dip)->devi_major);
1242 		return (DDI_FAILURE);
1243 	}
1244 
1245 	if (NEXUS_DRV(DEVI(dip)->devi_ops))
1246 		DEVI(dip)->devi_taskq = ddi_taskq_create(dip,
1247 		    "nexus_enum_tq", 1,
1248 		    TASKQ_DEFAULTPRI, 0);
1249 
1250 	mutex_enter(&(DEVI(dip)->devi_lock));
1251 	DEVI_SET_ATTACHING(dip);
1252 	DEVI_SET_NEED_RESET(dip);
1253 	mutex_exit(&(DEVI(dip)->devi_lock));
1254 
1255 	rv = devi_attach(dip, DDI_ATTACH);
1256 
1257 	mutex_enter(&(DEVI(dip)->devi_lock));
1258 	DEVI_CLR_ATTACHING(dip);
1259 
1260 	if (rv != DDI_SUCCESS) {
1261 		DEVI_CLR_NEED_RESET(dip);
1262 		mutex_exit(&DEVI(dip)->devi_lock);
1263 
1264 		/*
1265 		 * Cleanup dacf reservations
1266 		 */
1267 		mutex_enter(&dacf_lock);
1268 		dacf_clr_rsrvs(dip, DACF_OPID_POSTATTACH);
1269 		dacf_clr_rsrvs(dip, DACF_OPID_PREDETACH);
1270 		mutex_exit(&dacf_lock);
1271 		if (DEVI(dip)->devi_taskq)
1272 			ddi_taskq_destroy(DEVI(dip)->devi_taskq);
1273 		ddi_remove_minor_node(dip, NULL);
1274 
1275 		/* release the driver if attach failed */
1276 		ndi_rele_driver(dip);
1277 		DEVI(dip)->devi_ops = NULL;
1278 		NDI_CONFIG_DEBUG((CE_CONT, "attach_node: 0x%p(%s%d) failed\n",
1279 		    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1280 		return (DDI_FAILURE);
1281 	} else
1282 		mutex_exit(&DEVI(dip)->devi_lock);
1283 
1284 	/* successful attach, return with driver held */
1285 
1286 	return (DDI_SUCCESS);
1287 }
1288 
1289 /*
1290  * Detach devinfo node.
1291  * Per-driver list must be held busy.
1292  */
1293 static int
1294 detach_node(dev_info_t *dip, uint_t flag)
1295 {
1296 	struct devnames	*dnp;
1297 	int		rv;
1298 
1299 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
1300 	ASSERT(i_ddi_node_state(dip) == DS_ATTACHED);
1301 
1302 	/* check references */
1303 	if (DEVI(dip)->devi_ref)
1304 		return (DDI_FAILURE);
1305 
1306 	NDI_CONFIG_DEBUG((CE_CONT, "detach_node: 0x%p(%s%d)\n",
1307 	    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1308 
1309 	/*
1310 	 * NOTE: If we are processing a pHCI node then the calling code
1311 	 * must detect this and ndi_devi_enter() in (vHCI, parent(pHCI))
1312 	 * order unless pHCI and vHCI are siblings.  Code paths leading
1313 	 * here that must ensure this ordering include:
1314 	 * unconfig_immediate_children(), devi_unconfig_one(),
1315 	 * ndi_devi_unconfig_one(), ndi_devi_offline().
1316 	 */
1317 	ASSERT(!MDI_PHCI(dip) ||
1318 	    (ddi_get_parent(mdi_devi_get_vdip(dip)) == ddi_get_parent(dip)) ||
1319 	    DEVI_BUSY_OWNED(mdi_devi_get_vdip(dip)));
1320 
1321 	/* Offline the device node with the mpxio framework. */
1322 	if (mdi_devi_offline(dip, flag) != NDI_SUCCESS) {
1323 		return (DDI_FAILURE);
1324 	}
1325 
1326 	/* drain the taskq */
1327 	if (DEVI(dip)->devi_taskq)
1328 		ddi_taskq_wait(DEVI(dip)->devi_taskq);
1329 
1330 	rv = devi_detach(dip, DDI_DETACH);
1331 
1332 	if (rv != DDI_SUCCESS) {
1333 		NDI_CONFIG_DEBUG((CE_CONT,
1334 		    "detach_node: 0x%p(%s%d) failed\n",
1335 		    (void *)dip, ddi_driver_name(dip), ddi_get_instance(dip)));
1336 		return (DDI_FAILURE);
1337 	}
1338 
1339 	mutex_enter(&(DEVI(dip)->devi_lock));
1340 	DEVI_CLR_NEED_RESET(dip);
1341 	mutex_exit(&(DEVI(dip)->devi_lock));
1342 
1343 #if defined(__i386) || defined(__amd64)
1344 #if !defined(__xpv)
1345 	/*
1346 	 * Close any iommulib mediated linkage to an IOMMU
1347 	 */
1348 	iommulib_nex_close(dip);
1349 #endif
1350 #endif
1351 
1352 	/* destroy the taskq */
1353 	if (DEVI(dip)->devi_taskq) {
1354 		ddi_taskq_destroy(DEVI(dip)->devi_taskq);
1355 		DEVI(dip)->devi_taskq = NULL;
1356 	}
1357 
1358 	/* Cleanup dacf reservations */
1359 	mutex_enter(&dacf_lock);
1360 	dacf_clr_rsrvs(dip, DACF_OPID_POSTATTACH);
1361 	dacf_clr_rsrvs(dip, DACF_OPID_PREDETACH);
1362 	mutex_exit(&dacf_lock);
1363 
1364 	/* remove any additional flavors that were added */
1365 	if (DEVI(dip)->devi_flavorv_n > 1 && DEVI(dip)->devi_flavorv != NULL) {
1366 		kmem_free(DEVI(dip)->devi_flavorv,
1367 		    (DEVI(dip)->devi_flavorv_n - 1) * sizeof (void *));
1368 		DEVI(dip)->devi_flavorv = NULL;
1369 	}
1370 
1371 	/* Remove properties and minor nodes in case driver forgots */
1372 	ddi_remove_minor_node(dip, NULL);
1373 	ddi_prop_remove_all(dip);
1374 
1375 	/* a detached node can't have attached or .conf children */
1376 	mutex_enter(&DEVI(dip)->devi_lock);
1377 	DEVI(dip)->devi_flags &= ~(DEVI_MADE_CHILDREN|DEVI_ATTACHED_CHILDREN);
1378 	mutex_exit(&DEVI(dip)->devi_lock);
1379 
1380 	/*
1381 	 * If the instance has successfully detached in detach_driver() context,
1382 	 * clear DN_DRIVER_HELD for correct ddi_hold_installed_driver()
1383 	 * behavior. Consumers like qassociate() depend on this (via clnopen()).
1384 	 */
1385 	if (flag & NDI_DETACH_DRIVER) {
1386 		dnp = &(devnamesp[DEVI(dip)->devi_major]);
1387 		LOCK_DEV_OPS(&dnp->dn_lock);
1388 		dnp->dn_flags &= ~DN_DRIVER_HELD;
1389 		UNLOCK_DEV_OPS(&dnp->dn_lock);
1390 	}
1391 
1392 	/* successful detach, release the driver */
1393 	ndi_rele_driver(dip);
1394 	DEVI(dip)->devi_ops = NULL;
1395 	return (DDI_SUCCESS);
1396 }
1397 
1398 /*
1399  * Run dacf post_attach routines
1400  */
1401 static int
1402 postattach_node(dev_info_t *dip)
1403 {
1404 	int rval;
1405 
1406 	/*
1407 	 * For hotplug busses like USB, it's possible that devices
1408 	 * are removed but dip is still around. We don't want to
1409 	 * run dacf routines as part of detach failure recovery.
1410 	 *
1411 	 * Pretend success until we figure out how to prevent
1412 	 * access to such devinfo nodes.
1413 	 */
1414 	if (DEVI_IS_DEVICE_REMOVED(dip))
1415 		return (DDI_SUCCESS);
1416 
1417 	/*
1418 	 * if dacf_postattach failed, report it to the framework
1419 	 * so that it can be retried later at the open time.
1420 	 */
1421 	mutex_enter(&dacf_lock);
1422 	rval = dacfc_postattach(dip);
1423 	mutex_exit(&dacf_lock);
1424 
1425 	/*
1426 	 * Plumbing during postattach may fail because of the
1427 	 * underlying device is not ready. This will fail ndi_devi_config()
1428 	 * in dv_filldir() and a warning message is issued. The message
1429 	 * from here will explain what happened
1430 	 */
1431 	if (rval != DACF_SUCCESS) {
1432 		cmn_err(CE_WARN, "Postattach failed for %s%d\n",
1433 		    ddi_driver_name(dip), ddi_get_instance(dip));
1434 		return (DDI_FAILURE);
1435 	}
1436 
1437 	return (DDI_SUCCESS);
1438 }
1439 
1440 /*
1441  * Run dacf pre-detach routines
1442  */
1443 static int
1444 predetach_node(dev_info_t *dip, uint_t flag)
1445 {
1446 	int ret;
1447 
1448 	/*
1449 	 * Don't auto-detach if DDI_FORCEATTACH or DDI_NO_AUTODETACH
1450 	 * properties are set.
1451 	 */
1452 	if (flag & NDI_AUTODETACH) {
1453 		struct devnames *dnp;
1454 		int pflag = DDI_PROP_NOTPROM | DDI_PROP_DONTPASS;
1455 
1456 		if ((ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1457 		    pflag, DDI_FORCEATTACH, 0) == 1) ||
1458 		    (ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1459 		    pflag, DDI_NO_AUTODETACH, 0) == 1))
1460 			return (DDI_FAILURE);
1461 
1462 		/* check for driver global version of DDI_NO_AUTODETACH */
1463 		dnp = &devnamesp[DEVI(dip)->devi_major];
1464 		LOCK_DEV_OPS(&dnp->dn_lock);
1465 		if (dnp->dn_flags & DN_NO_AUTODETACH) {
1466 			UNLOCK_DEV_OPS(&dnp->dn_lock);
1467 			return (DDI_FAILURE);
1468 		}
1469 		UNLOCK_DEV_OPS(&dnp->dn_lock);
1470 	}
1471 
1472 	mutex_enter(&dacf_lock);
1473 	ret = dacfc_predetach(dip);
1474 	mutex_exit(&dacf_lock);
1475 
1476 	return (ret);
1477 }
1478 
1479 /*
1480  * Wrapper for making multiple state transitions
1481  */
1482 
1483 /*
1484  * i_ndi_config_node: upgrade dev_info node into a specified state.
1485  * It is a bit tricky because the locking protocol changes before and
1486  * after a node is bound to a driver. All locks are held external to
1487  * this function.
1488  */
1489 int
1490 i_ndi_config_node(dev_info_t *dip, ddi_node_state_t state, uint_t flag)
1491 {
1492 	_NOTE(ARGUNUSED(flag))
1493 	int rv = DDI_SUCCESS;
1494 
1495 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
1496 
1497 	while ((i_ddi_node_state(dip) < state) && (rv == DDI_SUCCESS)) {
1498 
1499 		/* don't allow any more changes to the device tree */
1500 		if (devinfo_freeze) {
1501 			rv = DDI_FAILURE;
1502 			break;
1503 		}
1504 
1505 		switch (i_ddi_node_state(dip)) {
1506 		case DS_PROTO:
1507 			/*
1508 			 * only caller can reference this node, no external
1509 			 * locking needed.
1510 			 */
1511 			link_node(dip);
1512 			i_ddi_set_node_state(dip, DS_LINKED);
1513 			break;
1514 		case DS_LINKED:
1515 			/*
1516 			 * Three code path may attempt to bind a node:
1517 			 * - boot code
1518 			 * - add_drv
1519 			 * - hotplug thread
1520 			 * Boot code is single threaded, add_drv synchronize
1521 			 * on a userland lock, and hotplug synchronize on
1522 			 * hotplug_lk. There could be a race between add_drv
1523 			 * and hotplug thread. We'll live with this until the
1524 			 * conversion to top-down loading.
1525 			 */
1526 			if ((rv = bind_node(dip)) == DDI_SUCCESS)
1527 				i_ddi_set_node_state(dip, DS_BOUND);
1528 
1529 			break;
1530 		case DS_BOUND:
1531 			/*
1532 			 * The following transitions synchronizes on the
1533 			 * per-driver busy changing flag, since we already
1534 			 * have a driver.
1535 			 */
1536 			if ((rv = init_node(dip)) == DDI_SUCCESS)
1537 				i_ddi_set_node_state(dip, DS_INITIALIZED);
1538 			break;
1539 		case DS_INITIALIZED:
1540 			if ((rv = probe_node(dip)) == DDI_SUCCESS)
1541 				i_ddi_set_node_state(dip, DS_PROBED);
1542 			break;
1543 		case DS_PROBED:
1544 			i_ddi_check_retire(dip);
1545 			atomic_add_long(&devinfo_attach_detach, 1);
1546 			if ((rv = attach_node(dip)) == DDI_SUCCESS)
1547 				i_ddi_set_node_state(dip, DS_ATTACHED);
1548 			atomic_add_long(&devinfo_attach_detach, -1);
1549 			break;
1550 		case DS_ATTACHED:
1551 			if ((rv = postattach_node(dip)) == DDI_SUCCESS)
1552 				i_ddi_set_node_state(dip, DS_READY);
1553 			break;
1554 		case DS_READY:
1555 			break;
1556 		default:
1557 			/* should never reach here */
1558 			ASSERT("unknown devinfo state");
1559 		}
1560 	}
1561 
1562 	if (ddidebug & DDI_AUDIT)
1563 		da_log_enter(dip);
1564 	return (rv);
1565 }
1566 
1567 /*
1568  * i_ndi_unconfig_node: downgrade dev_info node into a specified state.
1569  */
1570 int
1571 i_ndi_unconfig_node(dev_info_t *dip, ddi_node_state_t state, uint_t flag)
1572 {
1573 	int	rv = DDI_SUCCESS;
1574 
1575 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
1576 
1577 	while ((i_ddi_node_state(dip) > state) && (rv == DDI_SUCCESS)) {
1578 
1579 		/* don't allow any more changes to the device tree */
1580 		if (devinfo_freeze) {
1581 			rv = DDI_FAILURE;
1582 			break;
1583 		}
1584 
1585 		switch (i_ddi_node_state(dip)) {
1586 		case DS_PROTO:
1587 			break;
1588 		case DS_LINKED:
1589 			/*
1590 			 * Persistent nodes are only removed by hotplug code
1591 			 * .conf nodes synchronizes on per-driver list.
1592 			 */
1593 			if ((rv = unlink_node(dip)) == DDI_SUCCESS)
1594 				i_ddi_set_node_state(dip, DS_PROTO);
1595 			break;
1596 		case DS_BOUND:
1597 			/*
1598 			 * The following transitions synchronizes on the
1599 			 * per-driver busy changing flag, since we already
1600 			 * have a driver.
1601 			 */
1602 			if ((rv = unbind_node(dip)) == DDI_SUCCESS)
1603 				i_ddi_set_node_state(dip, DS_LINKED);
1604 			break;
1605 		case DS_INITIALIZED:
1606 			if ((rv = uninit_node(dip)) == DDI_SUCCESS)
1607 				i_ddi_set_node_state(dip, DS_BOUND);
1608 			break;
1609 		case DS_PROBED:
1610 			if ((rv = unprobe_node(dip)) == DDI_SUCCESS)
1611 				i_ddi_set_node_state(dip, DS_INITIALIZED);
1612 			break;
1613 		case DS_ATTACHED:
1614 			atomic_add_long(&devinfo_attach_detach, 1);
1615 
1616 			mutex_enter(&(DEVI(dip)->devi_lock));
1617 			DEVI_SET_DETACHING(dip);
1618 			mutex_exit(&(DEVI(dip)->devi_lock));
1619 
1620 			membar_enter();	/* ensure visibility for hold_devi */
1621 
1622 			if ((rv = detach_node(dip, flag)) == DDI_SUCCESS)
1623 				i_ddi_set_node_state(dip, DS_PROBED);
1624 
1625 			mutex_enter(&(DEVI(dip)->devi_lock));
1626 			DEVI_CLR_DETACHING(dip);
1627 			mutex_exit(&(DEVI(dip)->devi_lock));
1628 
1629 			atomic_add_long(&devinfo_attach_detach, -1);
1630 			break;
1631 		case DS_READY:
1632 			if ((rv = predetach_node(dip, flag)) == DDI_SUCCESS)
1633 				i_ddi_set_node_state(dip, DS_ATTACHED);
1634 			break;
1635 		default:
1636 			ASSERT("unknown devinfo state");
1637 		}
1638 	}
1639 	da_log_enter(dip);
1640 	return (rv);
1641 }
1642 
1643 /*
1644  * ddi_initchild: transform node to DS_INITIALIZED state
1645  */
1646 int
1647 ddi_initchild(dev_info_t *parent, dev_info_t *proto)
1648 {
1649 	int ret, circ;
1650 
1651 	ndi_devi_enter(parent, &circ);
1652 	ret = i_ndi_config_node(proto, DS_INITIALIZED, 0);
1653 	ndi_devi_exit(parent, circ);
1654 
1655 	return (ret);
1656 }
1657 
1658 /*
1659  * ddi_uninitchild: transform node down to DS_BOUND state
1660  */
1661 int
1662 ddi_uninitchild(dev_info_t *dip)
1663 {
1664 	int ret, circ;
1665 	dev_info_t *parent = ddi_get_parent(dip);
1666 	ASSERT(parent);
1667 
1668 	ndi_devi_enter(parent, &circ);
1669 	ret = i_ndi_unconfig_node(dip, DS_BOUND, 0);
1670 	ndi_devi_exit(parent, circ);
1671 
1672 	return (ret);
1673 }
1674 
1675 /*
1676  * i_ddi_attachchild: transform node to DS_READY/i_ddi_devi_attached() state
1677  */
1678 static int
1679 i_ddi_attachchild(dev_info_t *dip)
1680 {
1681 	dev_info_t	*parent = ddi_get_parent(dip);
1682 	int		ret;
1683 
1684 	ASSERT(parent && DEVI_BUSY_OWNED(parent));
1685 
1686 	if ((i_ddi_node_state(dip) < DS_BOUND) || DEVI_IS_DEVICE_OFFLINE(dip))
1687 		return (DDI_FAILURE);
1688 
1689 	ret = i_ndi_config_node(dip, DS_READY, 0);
1690 	if (ret == NDI_SUCCESS) {
1691 		ret = DDI_SUCCESS;
1692 	} else {
1693 		/*
1694 		 * Take it down to DS_INITIALIZED so pm_pre_probe is run
1695 		 * on the next attach
1696 		 */
1697 		(void) i_ndi_unconfig_node(dip, DS_INITIALIZED, 0);
1698 		ret = DDI_FAILURE;
1699 	}
1700 
1701 	return (ret);
1702 }
1703 
1704 /*
1705  * i_ddi_detachchild: transform node down to DS_PROBED state
1706  *	If it fails, put it back to DS_READY state.
1707  * NOTE: A node that fails detach may be at DS_ATTACHED instead
1708  * of DS_READY for a small amount of time - this is the source of
1709  * transient DS_READY->DS_ATTACHED->DS_READY state changes.
1710  */
1711 static int
1712 i_ddi_detachchild(dev_info_t *dip, uint_t flags)
1713 {
1714 	dev_info_t	*parent = ddi_get_parent(dip);
1715 	int		ret;
1716 
1717 	ASSERT(parent && DEVI_BUSY_OWNED(parent));
1718 
1719 	ret = i_ndi_unconfig_node(dip, DS_PROBED, flags);
1720 	if (ret != DDI_SUCCESS)
1721 		(void) i_ndi_config_node(dip, DS_READY, 0);
1722 	else
1723 		/* allow pm_pre_probe to reestablish pm state */
1724 		(void) i_ndi_unconfig_node(dip, DS_INITIALIZED, 0);
1725 	return (ret);
1726 }
1727 
1728 /*
1729  * Add a child and bind to driver
1730  */
1731 dev_info_t *
1732 ddi_add_child(dev_info_t *pdip, char *name, uint_t nodeid, uint_t unit)
1733 {
1734 	int circ;
1735 	dev_info_t *dip;
1736 
1737 	/* allocate a new node */
1738 	dip = i_ddi_alloc_node(pdip, name, nodeid, (int)unit, NULL, KM_SLEEP);
1739 
1740 	ndi_devi_enter(pdip, &circ);
1741 	(void) i_ndi_config_node(dip, DS_BOUND, 0);
1742 	ndi_devi_exit(pdip, circ);
1743 	return (dip);
1744 }
1745 
1746 /*
1747  * ddi_remove_child: remove the dip. The parent must be attached and held
1748  */
1749 int
1750 ddi_remove_child(dev_info_t *dip, int dummy)
1751 {
1752 	_NOTE(ARGUNUSED(dummy))
1753 	int circ, ret;
1754 	dev_info_t *parent = ddi_get_parent(dip);
1755 	ASSERT(parent);
1756 
1757 	ndi_devi_enter(parent, &circ);
1758 
1759 	/*
1760 	 * If we still have children, for example SID nodes marked
1761 	 * as persistent but not attached, attempt to remove them.
1762 	 */
1763 	if (DEVI(dip)->devi_child) {
1764 		ret = ndi_devi_unconfig(dip, NDI_DEVI_REMOVE);
1765 		if (ret != NDI_SUCCESS) {
1766 			ndi_devi_exit(parent, circ);
1767 			return (DDI_FAILURE);
1768 		}
1769 		ASSERT(DEVI(dip)->devi_child == NULL);
1770 	}
1771 
1772 	ret = i_ndi_unconfig_node(dip, DS_PROTO, 0);
1773 	ndi_devi_exit(parent, circ);
1774 
1775 	if (ret != DDI_SUCCESS)
1776 		return (ret);
1777 
1778 	ASSERT(i_ddi_node_state(dip) == DS_PROTO);
1779 	i_ddi_free_node(dip);
1780 	return (DDI_SUCCESS);
1781 }
1782 
1783 /*
1784  * NDI wrappers for ref counting, node allocation, and transitions
1785  */
1786 
1787 /*
1788  * Hold/release the devinfo node itself.
1789  * Caller is assumed to prevent the devi from detaching during this call
1790  */
1791 void
1792 ndi_hold_devi(dev_info_t *dip)
1793 {
1794 	mutex_enter(&DEVI(dip)->devi_lock);
1795 	ASSERT(DEVI(dip)->devi_ref >= 0);
1796 	DEVI(dip)->devi_ref++;
1797 	membar_enter();			/* make sure stores are flushed */
1798 	mutex_exit(&DEVI(dip)->devi_lock);
1799 }
1800 
1801 void
1802 ndi_rele_devi(dev_info_t *dip)
1803 {
1804 	ASSERT(DEVI(dip)->devi_ref > 0);
1805 
1806 	mutex_enter(&DEVI(dip)->devi_lock);
1807 	DEVI(dip)->devi_ref--;
1808 	membar_enter();			/* make sure stores are flushed */
1809 	mutex_exit(&DEVI(dip)->devi_lock);
1810 }
1811 
1812 int
1813 e_ddi_devi_holdcnt(dev_info_t *dip)
1814 {
1815 	return (DEVI(dip)->devi_ref);
1816 }
1817 
1818 /*
1819  * Hold/release the driver the devinfo node is bound to.
1820  */
1821 struct dev_ops *
1822 ndi_hold_driver(dev_info_t *dip)
1823 {
1824 	if (i_ddi_node_state(dip) < DS_BOUND)
1825 		return (NULL);
1826 
1827 	ASSERT(DEVI(dip)->devi_major != -1);
1828 	return (mod_hold_dev_by_major(DEVI(dip)->devi_major));
1829 }
1830 
1831 void
1832 ndi_rele_driver(dev_info_t *dip)
1833 {
1834 	ASSERT(i_ddi_node_state(dip) >= DS_BOUND);
1835 	mod_rele_dev_by_major(DEVI(dip)->devi_major);
1836 }
1837 
1838 /*
1839  * Single thread entry into devinfo node for modifying its children (devinfo,
1840  * pathinfo, and minor). To verify in ASSERTS use DEVI_BUSY_OWNED macro.
1841  */
1842 void
1843 ndi_devi_enter(dev_info_t *dip, int *circular)
1844 {
1845 	struct dev_info *devi = DEVI(dip);
1846 	ASSERT(dip != NULL);
1847 
1848 	/* for vHCI, enforce (vHCI, pHCI) ndi_deve_enter() order */
1849 	ASSERT(!MDI_VHCI(dip) || (mdi_devi_pdip_entered(dip) == 0) ||
1850 	    DEVI_BUSY_OWNED(dip));
1851 
1852 	mutex_enter(&devi->devi_lock);
1853 	if (devi->devi_busy_thread == curthread) {
1854 		devi->devi_circular++;
1855 	} else {
1856 		while (DEVI_BUSY_CHANGING(devi) && !panicstr)
1857 			cv_wait(&(devi->devi_cv), &(devi->devi_lock));
1858 		if (panicstr) {
1859 			mutex_exit(&devi->devi_lock);
1860 			return;
1861 		}
1862 		devi->devi_flags |= DEVI_BUSY;
1863 		devi->devi_busy_thread = curthread;
1864 	}
1865 	*circular = devi->devi_circular;
1866 	mutex_exit(&devi->devi_lock);
1867 }
1868 
1869 /*
1870  * Release ndi_devi_enter or successful ndi_devi_tryenter.
1871  */
1872 void
1873 ndi_devi_exit(dev_info_t *dip, int circular)
1874 {
1875 	struct dev_info	*devi = DEVI(dip);
1876 	struct dev_info	*vdevi;
1877 	ASSERT(dip != NULL);
1878 
1879 	if (panicstr)
1880 		return;
1881 
1882 	mutex_enter(&(devi->devi_lock));
1883 	if (circular != 0) {
1884 		devi->devi_circular--;
1885 	} else {
1886 		devi->devi_flags &= ~DEVI_BUSY;
1887 		ASSERT(devi->devi_busy_thread == curthread);
1888 		devi->devi_busy_thread = NULL;
1889 		cv_broadcast(&(devi->devi_cv));
1890 	}
1891 	mutex_exit(&(devi->devi_lock));
1892 
1893 	/*
1894 	 * For pHCI exit we issue a broadcast to vHCI for ndi_devi_config_one()
1895 	 * doing cv_wait on vHCI.
1896 	 */
1897 	if (MDI_PHCI(dip)) {
1898 		vdevi = DEVI(mdi_devi_get_vdip(dip));
1899 		if (vdevi) {
1900 			mutex_enter(&(vdevi->devi_lock));
1901 			if (vdevi->devi_flags & DEVI_PHCI_SIGNALS_VHCI) {
1902 				vdevi->devi_flags &= ~DEVI_PHCI_SIGNALS_VHCI;
1903 				cv_broadcast(&(vdevi->devi_cv));
1904 			}
1905 			mutex_exit(&(vdevi->devi_lock));
1906 		}
1907 	}
1908 }
1909 
1910 /*
1911  * Release ndi_devi_enter and wait for possibility of new children, avoiding
1912  * possibility of missing broadcast before getting to cv_timedwait().
1913  */
1914 static void
1915 ndi_devi_exit_and_wait(dev_info_t *dip, int circular, clock_t end_time)
1916 {
1917 	struct dev_info	*devi = DEVI(dip);
1918 	ASSERT(dip != NULL);
1919 
1920 	if (panicstr)
1921 		return;
1922 
1923 	/*
1924 	 * We are called to wait for of a new child, and new child can
1925 	 * only be added if circular is zero.
1926 	 */
1927 	ASSERT(circular == 0);
1928 
1929 	/* like ndi_devi_exit with circular of zero */
1930 	mutex_enter(&(devi->devi_lock));
1931 	devi->devi_flags &= ~DEVI_BUSY;
1932 	ASSERT(devi->devi_busy_thread == curthread);
1933 	devi->devi_busy_thread = NULL;
1934 	cv_broadcast(&(devi->devi_cv));
1935 
1936 	/* now wait for new children while still holding devi_lock */
1937 	(void) cv_timedwait(&devi->devi_cv, &(devi->devi_lock), end_time);
1938 	mutex_exit(&(devi->devi_lock));
1939 }
1940 
1941 /*
1942  * Attempt to single thread entry into devinfo node for modifying its children.
1943  */
1944 int
1945 ndi_devi_tryenter(dev_info_t *dip, int *circular)
1946 {
1947 	int rval = 1;		   /* assume we enter */
1948 	struct dev_info *devi = DEVI(dip);
1949 	ASSERT(dip != NULL);
1950 
1951 	mutex_enter(&devi->devi_lock);
1952 	if (devi->devi_busy_thread == (void *)curthread) {
1953 		devi->devi_circular++;
1954 	} else {
1955 		if (!DEVI_BUSY_CHANGING(devi)) {
1956 			devi->devi_flags |= DEVI_BUSY;
1957 			devi->devi_busy_thread = (void *)curthread;
1958 		} else {
1959 			rval = 0;	/* devi is busy */
1960 		}
1961 	}
1962 	*circular = devi->devi_circular;
1963 	mutex_exit(&devi->devi_lock);
1964 	return (rval);
1965 }
1966 
1967 /*
1968  * Allocate and initialize a new dev_info structure.
1969  *
1970  * This routine may be called at interrupt time by a nexus in
1971  * response to a hotplug event, therefore memory allocations are
1972  * not allowed to sleep.
1973  */
1974 int
1975 ndi_devi_alloc(dev_info_t *parent, char *node_name, pnode_t nodeid,
1976     dev_info_t **ret_dip)
1977 {
1978 	ASSERT(node_name != NULL);
1979 	ASSERT(ret_dip != NULL);
1980 
1981 	*ret_dip = i_ddi_alloc_node(parent, node_name, nodeid, -1, NULL,
1982 	    KM_NOSLEEP);
1983 	if (*ret_dip == NULL) {
1984 		return (NDI_NOMEM);
1985 	}
1986 
1987 	return (NDI_SUCCESS);
1988 }
1989 
1990 /*
1991  * Allocate and initialize a new dev_info structure
1992  * This routine may sleep and should not be called at interrupt time
1993  */
1994 void
1995 ndi_devi_alloc_sleep(dev_info_t *parent, char *node_name, pnode_t nodeid,
1996     dev_info_t **ret_dip)
1997 {
1998 	ASSERT(node_name != NULL);
1999 	ASSERT(ret_dip != NULL);
2000 
2001 	*ret_dip = i_ddi_alloc_node(parent, node_name, nodeid, -1, NULL,
2002 	    KM_SLEEP);
2003 	ASSERT(*ret_dip);
2004 }
2005 
2006 /*
2007  * Remove an initialized (but not yet attached) dev_info
2008  * node from it's parent.
2009  */
2010 int
2011 ndi_devi_free(dev_info_t *dip)
2012 {
2013 	ASSERT(dip != NULL);
2014 
2015 	if (i_ddi_node_state(dip) >= DS_INITIALIZED)
2016 		return (DDI_FAILURE);
2017 
2018 	NDI_CONFIG_DEBUG((CE_CONT, "ndi_devi_free: %s%d (%p)\n",
2019 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip));
2020 
2021 	(void) ddi_remove_child(dip, 0);
2022 
2023 	return (NDI_SUCCESS);
2024 }
2025 
2026 /*
2027  * ndi_devi_bind_driver() binds a driver to a given device. If it fails
2028  * to bind the driver, it returns an appropriate error back. Some drivers
2029  * may want to know if the actually failed to bind.
2030  */
2031 int
2032 ndi_devi_bind_driver(dev_info_t *dip, uint_t flags)
2033 {
2034 	int ret = NDI_FAILURE;
2035 	int circ;
2036 	dev_info_t *pdip = ddi_get_parent(dip);
2037 	ASSERT(pdip);
2038 
2039 	NDI_CONFIG_DEBUG((CE_CONT,
2040 	    "ndi_devi_bind_driver: %s%d (%p) flags: %x\n",
2041 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
2042 
2043 	ndi_devi_enter(pdip, &circ);
2044 	if (i_ndi_config_node(dip, DS_BOUND, flags) == DDI_SUCCESS)
2045 		ret = NDI_SUCCESS;
2046 	ndi_devi_exit(pdip, circ);
2047 
2048 	return (ret);
2049 }
2050 
2051 /*
2052  * ndi_devi_unbind_driver: unbind the dip
2053  */
2054 static int
2055 ndi_devi_unbind_driver(dev_info_t *dip)
2056 {
2057 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
2058 
2059 	return (i_ndi_unconfig_node(dip, DS_LINKED, 0));
2060 }
2061 
2062 /*
2063  * Misc. help routines called by framework only
2064  */
2065 
2066 /*
2067  * Get the state of node
2068  */
2069 ddi_node_state_t
2070 i_ddi_node_state(dev_info_t *dip)
2071 {
2072 	return (DEVI(dip)->devi_node_state);
2073 }
2074 
2075 /*
2076  * Set the state of node
2077  */
2078 void
2079 i_ddi_set_node_state(dev_info_t *dip, ddi_node_state_t state)
2080 {
2081 	DEVI(dip)->devi_node_state = state;
2082 	membar_enter();			/* make sure stores are flushed */
2083 }
2084 
2085 /*
2086  * Determine if node is attached. The implementation accommodates transient
2087  * DS_READY->DS_ATTACHED->DS_READY state changes.  Outside this file, this
2088  * function should be instead of i_ddi_node_state() DS_ATTACHED/DS_READY
2089  * state checks.
2090  */
2091 int
2092 i_ddi_devi_attached(dev_info_t *dip)
2093 {
2094 	return (DEVI(dip)->devi_node_state >= DS_ATTACHED);
2095 }
2096 
2097 /*
2098  * Common function for finding a node in a sibling list given name and addr.
2099  *
2100  * By default, name is matched with devi_node_name. The following
2101  * alternative match strategies are supported:
2102  *
2103  *	FIND_NODE_BY_NODENAME: Match on node name - typical use.
2104  *
2105  *	FIND_NODE_BY_DRIVER: A match on driver name bound to node is conducted.
2106  *		This support is used for support of OBP generic names and
2107  *		for the conversion from driver names to generic names. When
2108  *		more consistency in the generic name environment is achieved
2109  *		(and not needed for upgrade) this support can be removed.
2110  *
2111  *	FIND_NODE_BY_ADDR: Match on just the addr.
2112  *		This support is only used/needed during boot to match
2113  *		a node bound via a path-based driver alias.
2114  *
2115  * If a child is not named (dev_addr == NULL), there are three
2116  * possible actions:
2117  *
2118  *	(1) skip it
2119  *	(2) FIND_ADDR_BY_INIT: bring child to DS_INITIALIZED state
2120  *	(3) FIND_ADDR_BY_CALLBACK: use a caller-supplied callback function
2121  */
2122 #define	FIND_NODE_BY_NODENAME	0x01
2123 #define	FIND_NODE_BY_DRIVER	0x02
2124 #define	FIND_NODE_BY_ADDR	0x04
2125 #define	FIND_ADDR_BY_INIT	0x10
2126 #define	FIND_ADDR_BY_CALLBACK	0x20
2127 
2128 static dev_info_t *
2129 find_sibling(dev_info_t *head, char *cname, char *caddr, uint_t flag,
2130     int (*callback)(dev_info_t *, char *, int))
2131 {
2132 	dev_info_t	*dip;
2133 	char		*addr, *buf;
2134 	major_t		major;
2135 	uint_t		by;
2136 
2137 	/* only one way to find a node */
2138 	by = flag &
2139 	    (FIND_NODE_BY_DRIVER | FIND_NODE_BY_NODENAME | FIND_NODE_BY_ADDR);
2140 	ASSERT(by && BIT_ONLYONESET(by));
2141 
2142 	/* only one way to name a node */
2143 	ASSERT(((flag & FIND_ADDR_BY_INIT) == 0) ||
2144 	    ((flag & FIND_ADDR_BY_CALLBACK) == 0));
2145 
2146 	if (by == FIND_NODE_BY_DRIVER) {
2147 		major = ddi_name_to_major(cname);
2148 		if (major == DDI_MAJOR_T_NONE)
2149 			return (NULL);
2150 	}
2151 
2152 	/* preallocate buffer of naming node by callback */
2153 	if (flag & FIND_ADDR_BY_CALLBACK)
2154 		buf = kmem_alloc(MAXNAMELEN, KM_SLEEP);
2155 
2156 	/*
2157 	 * Walk the child list to find a match
2158 	 */
2159 	if (head == NULL)
2160 		return (NULL);
2161 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(head)));
2162 	for (dip = head; dip; dip = ddi_get_next_sibling(dip)) {
2163 		if (by == FIND_NODE_BY_NODENAME) {
2164 			/* match node name */
2165 			if (strcmp(cname, DEVI(dip)->devi_node_name) != 0)
2166 				continue;
2167 		} else if (by == FIND_NODE_BY_DRIVER) {
2168 			/* match driver major */
2169 			if (DEVI(dip)->devi_major != major)
2170 				continue;
2171 		}
2172 
2173 		if ((addr = DEVI(dip)->devi_addr) == NULL) {
2174 			/* name the child based on the flag */
2175 			if (flag & FIND_ADDR_BY_INIT) {
2176 				if (ddi_initchild(ddi_get_parent(dip), dip)
2177 				    != DDI_SUCCESS)
2178 					continue;
2179 				addr = DEVI(dip)->devi_addr;
2180 			} else if (flag & FIND_ADDR_BY_CALLBACK) {
2181 				if ((callback == NULL) || (callback(
2182 				    dip, buf, MAXNAMELEN) != DDI_SUCCESS))
2183 					continue;
2184 				addr = buf;
2185 			} else {
2186 				continue;	/* skip */
2187 			}
2188 		}
2189 
2190 		/* match addr */
2191 		ASSERT(addr != NULL);
2192 		if (strcmp(caddr, addr) == 0)
2193 			break;	/* node found */
2194 
2195 	}
2196 	if (flag & FIND_ADDR_BY_CALLBACK)
2197 		kmem_free(buf, MAXNAMELEN);
2198 	return (dip);
2199 }
2200 
2201 /*
2202  * Find child of pdip with name: cname@caddr
2203  * Called by init_node() to look for duplicate nodes
2204  */
2205 static dev_info_t *
2206 find_duplicate_child(dev_info_t *pdip, dev_info_t *dip)
2207 {
2208 	dev_info_t *dup;
2209 	char *cname = DEVI(dip)->devi_node_name;
2210 	char *caddr = DEVI(dip)->devi_addr;
2211 
2212 	/* search nodes before dip */
2213 	dup = find_sibling(ddi_get_child(pdip), cname, caddr,
2214 	    FIND_NODE_BY_NODENAME, NULL);
2215 	if (dup != dip)
2216 		return (dup);
2217 
2218 	/*
2219 	 * search nodes after dip; normally this is not needed,
2220 	 */
2221 	return (find_sibling(ddi_get_next_sibling(dip), cname, caddr,
2222 	    FIND_NODE_BY_NODENAME, NULL));
2223 }
2224 
2225 /*
2226  * Find a child of a given name and address, using a callback to name
2227  * unnamed children. cname is the binding name.
2228  */
2229 dev_info_t *
2230 ndi_devi_findchild_by_callback(dev_info_t *pdip, char *dname, char *ua,
2231     int (*make_ua)(dev_info_t *, char *, int))
2232 {
2233 	int	by = FIND_ADDR_BY_CALLBACK;
2234 
2235 	ASSERT(DEVI_BUSY_OWNED(pdip));
2236 	by |= dname ? FIND_NODE_BY_DRIVER : FIND_NODE_BY_ADDR;
2237 	return (find_sibling(ddi_get_child(pdip), dname, ua, by, make_ua));
2238 }
2239 
2240 /*
2241  * Find a child of a given name and address, invoking initchild to name
2242  * unnamed children. cname is the node name.
2243  */
2244 static dev_info_t *
2245 find_child_by_name(dev_info_t *pdip, char *cname, char *caddr)
2246 {
2247 	dev_info_t	*dip;
2248 
2249 	/* attempt search without changing state of preceding siblings */
2250 	dip = find_sibling(ddi_get_child(pdip), cname, caddr,
2251 	    FIND_NODE_BY_NODENAME, NULL);
2252 	if (dip)
2253 		return (dip);
2254 
2255 	return (find_sibling(ddi_get_child(pdip), cname, caddr,
2256 	    FIND_NODE_BY_NODENAME|FIND_ADDR_BY_INIT, NULL));
2257 }
2258 
2259 /*
2260  * Find a child of a given name and address, invoking initchild to name
2261  * unnamed children. cname is the node name.
2262  */
2263 static dev_info_t *
2264 find_child_by_driver(dev_info_t *pdip, char *cname, char *caddr)
2265 {
2266 	dev_info_t	*dip;
2267 
2268 	/* attempt search without changing state of preceding siblings */
2269 	dip = find_sibling(ddi_get_child(pdip), cname, caddr,
2270 	    FIND_NODE_BY_DRIVER, NULL);
2271 	if (dip)
2272 		return (dip);
2273 
2274 	return (find_sibling(ddi_get_child(pdip), cname, caddr,
2275 	    FIND_NODE_BY_DRIVER|FIND_ADDR_BY_INIT, NULL));
2276 }
2277 
2278 /*
2279  * Find a child of a given address, invoking initchild to name
2280  * unnamed children. cname is the node name.
2281  *
2282  * NOTE: This function is only used during boot. One would hope that
2283  * unique sibling unit-addresses on hardware branches of the tree would
2284  * be a requirement to avoid two drivers trying to control the same
2285  * piece of hardware. Unfortunately there are some cases where this
2286  * situation exists (/ssm@0,0/pci@1c,700000 /ssm@0,0/sghsc@1c,700000).
2287  * Until unit-address uniqueness of siblings is guaranteed, use of this
2288  * interface for purposes other than boot should be avoided.
2289  */
2290 static dev_info_t *
2291 find_child_by_addr(dev_info_t *pdip, char *caddr)
2292 {
2293 	dev_info_t	*dip;
2294 
2295 	/* return NULL if called without a unit-address */
2296 	if ((caddr == NULL) || (*caddr == '\0'))
2297 		return (NULL);
2298 
2299 	/* attempt search without changing state of preceding siblings */
2300 	dip = find_sibling(ddi_get_child(pdip), NULL, caddr,
2301 	    FIND_NODE_BY_ADDR, NULL);
2302 	if (dip)
2303 		return (dip);
2304 
2305 	return (find_sibling(ddi_get_child(pdip), NULL, caddr,
2306 	    FIND_NODE_BY_ADDR|FIND_ADDR_BY_INIT, NULL));
2307 }
2308 
2309 /*
2310  * Deleting a property list. Take care, since some property structures
2311  * may not be fully built.
2312  */
2313 void
2314 i_ddi_prop_list_delete(ddi_prop_t *prop)
2315 {
2316 	while (prop) {
2317 		ddi_prop_t *next = prop->prop_next;
2318 		if (prop->prop_name)
2319 			kmem_free(prop->prop_name, strlen(prop->prop_name) + 1);
2320 		if ((prop->prop_len != 0) && prop->prop_val)
2321 			kmem_free(prop->prop_val, prop->prop_len);
2322 		kmem_free(prop, sizeof (struct ddi_prop));
2323 		prop = next;
2324 	}
2325 }
2326 
2327 /*
2328  * Duplicate property list
2329  */
2330 ddi_prop_t *
2331 i_ddi_prop_list_dup(ddi_prop_t *prop, uint_t flag)
2332 {
2333 	ddi_prop_t *result, *prev, *copy;
2334 
2335 	if (prop == NULL)
2336 		return (NULL);
2337 
2338 	result = prev = NULL;
2339 	for (; prop != NULL; prop = prop->prop_next) {
2340 		ASSERT(prop->prop_name != NULL);
2341 		copy = kmem_zalloc(sizeof (struct ddi_prop), flag);
2342 		if (copy == NULL)
2343 			goto fail;
2344 
2345 		copy->prop_dev = prop->prop_dev;
2346 		copy->prop_flags = prop->prop_flags;
2347 		copy->prop_name = i_ddi_strdup(prop->prop_name, flag);
2348 		if (copy->prop_name == NULL)
2349 			goto fail;
2350 
2351 		if ((copy->prop_len = prop->prop_len) != 0) {
2352 			copy->prop_val = kmem_zalloc(prop->prop_len, flag);
2353 			if (copy->prop_val == NULL)
2354 				goto fail;
2355 
2356 			bcopy(prop->prop_val, copy->prop_val, prop->prop_len);
2357 		}
2358 
2359 		if (prev == NULL)
2360 			result = prev = copy;
2361 		else
2362 			prev->prop_next = copy;
2363 		prev = copy;
2364 	}
2365 	return (result);
2366 
2367 fail:
2368 	i_ddi_prop_list_delete(result);
2369 	return (NULL);
2370 }
2371 
2372 /*
2373  * Create a reference property list, currently used only for
2374  * driver global properties. Created with ref count of 1.
2375  */
2376 ddi_prop_list_t *
2377 i_ddi_prop_list_create(ddi_prop_t *props)
2378 {
2379 	ddi_prop_list_t *list = kmem_alloc(sizeof (*list), KM_SLEEP);
2380 	list->prop_list = props;
2381 	list->prop_ref = 1;
2382 	return (list);
2383 }
2384 
2385 /*
2386  * Increment/decrement reference count. The reference is
2387  * protected by dn_lock. The only interfaces modifying
2388  * dn_global_prop_ptr is in impl_make[free]_parlist().
2389  */
2390 void
2391 i_ddi_prop_list_hold(ddi_prop_list_t *prop_list, struct devnames *dnp)
2392 {
2393 	ASSERT(prop_list->prop_ref >= 0);
2394 	ASSERT(mutex_owned(&dnp->dn_lock));
2395 	prop_list->prop_ref++;
2396 }
2397 
2398 void
2399 i_ddi_prop_list_rele(ddi_prop_list_t *prop_list, struct devnames *dnp)
2400 {
2401 	ASSERT(prop_list->prop_ref > 0);
2402 	ASSERT(mutex_owned(&dnp->dn_lock));
2403 	prop_list->prop_ref--;
2404 
2405 	if (prop_list->prop_ref == 0) {
2406 		i_ddi_prop_list_delete(prop_list->prop_list);
2407 		kmem_free(prop_list, sizeof (*prop_list));
2408 	}
2409 }
2410 
2411 /*
2412  * Free table of classes by drivers
2413  */
2414 void
2415 i_ddi_free_exported_classes(char **classes, int n)
2416 {
2417 	if ((n == 0) || (classes == NULL))
2418 		return;
2419 
2420 	kmem_free(classes, n * sizeof (char *));
2421 }
2422 
2423 /*
2424  * Get all classes exported by dip
2425  */
2426 int
2427 i_ddi_get_exported_classes(dev_info_t *dip, char ***classes)
2428 {
2429 	extern void lock_hw_class_list();
2430 	extern void unlock_hw_class_list();
2431 	extern int get_class(const char *, char **);
2432 
2433 	static char *rootclass = "root";
2434 	int n = 0, nclass = 0;
2435 	char **buf;
2436 
2437 	ASSERT(i_ddi_node_state(dip) >= DS_BOUND);
2438 
2439 	if (dip == ddi_root_node())	/* rootnode exports class "root" */
2440 		nclass = 1;
2441 	lock_hw_class_list();
2442 	nclass += get_class(ddi_driver_name(dip), NULL);
2443 	if (nclass == 0) {
2444 		unlock_hw_class_list();
2445 		return (0);		/* no class exported */
2446 	}
2447 
2448 	*classes = buf = kmem_alloc(nclass * sizeof (char *), KM_SLEEP);
2449 	if (dip == ddi_root_node()) {
2450 		*buf++ = rootclass;
2451 		n = 1;
2452 	}
2453 	n += get_class(ddi_driver_name(dip), buf);
2454 	unlock_hw_class_list();
2455 
2456 	ASSERT(n == nclass);    /* make sure buf wasn't overrun */
2457 	return (nclass);
2458 }
2459 
2460 /*
2461  * Helper functions, returns NULL if no memory.
2462  */
2463 char *
2464 i_ddi_strdup(char *str, uint_t flag)
2465 {
2466 	char *copy;
2467 
2468 	if (str == NULL)
2469 		return (NULL);
2470 
2471 	copy = kmem_alloc(strlen(str) + 1, flag);
2472 	if (copy == NULL)
2473 		return (NULL);
2474 
2475 	(void) strcpy(copy, str);
2476 	return (copy);
2477 }
2478 
2479 /*
2480  * Load driver.conf file for major. Load all if major == -1.
2481  *
2482  * This is called
2483  * - early in boot after devnames array is initialized
2484  * - from vfs code when certain file systems are mounted
2485  * - from add_drv when a new driver is added
2486  */
2487 int
2488 i_ddi_load_drvconf(major_t major)
2489 {
2490 	extern int modrootloaded;
2491 
2492 	major_t low, high, m;
2493 
2494 	if (major == DDI_MAJOR_T_NONE) {
2495 		low = 0;
2496 		high = devcnt - 1;
2497 	} else {
2498 		if (major >= devcnt)
2499 			return (EINVAL);
2500 		low = high = major;
2501 	}
2502 
2503 	for (m = low; m <= high; m++) {
2504 		struct devnames *dnp = &devnamesp[m];
2505 		LOCK_DEV_OPS(&dnp->dn_lock);
2506 		dnp->dn_flags &= ~DN_DRIVER_HELD;
2507 		(void) impl_make_parlist(m);
2508 		UNLOCK_DEV_OPS(&dnp->dn_lock);
2509 	}
2510 
2511 	if (modrootloaded) {
2512 		ddi_walk_devs(ddi_root_node(), reset_nexus_flags,
2513 		    (void *)(uintptr_t)major);
2514 	}
2515 
2516 	/* build dn_list from old entries in path_to_inst */
2517 	e_ddi_unorphan_instance_nos();
2518 	return (0);
2519 }
2520 
2521 /*
2522  * Unload a specific driver.conf.
2523  * Don't support unload all because it doesn't make any sense
2524  */
2525 int
2526 i_ddi_unload_drvconf(major_t major)
2527 {
2528 	int error;
2529 	struct devnames *dnp;
2530 
2531 	if (major >= devcnt)
2532 		return (EINVAL);
2533 
2534 	/*
2535 	 * Take the per-driver lock while unloading driver.conf
2536 	 */
2537 	dnp = &devnamesp[major];
2538 	LOCK_DEV_OPS(&dnp->dn_lock);
2539 	error = impl_free_parlist(major);
2540 	UNLOCK_DEV_OPS(&dnp->dn_lock);
2541 	return (error);
2542 }
2543 
2544 /*
2545  * Merge a .conf node. This is called by nexus drivers to augment
2546  * hw node with properties specified in driver.conf file. This function
2547  * takes a callback routine to name nexus children.
2548  * The parent node must be held busy.
2549  *
2550  * It returns DDI_SUCCESS if the node is merged and DDI_FAILURE otherwise.
2551  */
2552 int
2553 ndi_merge_node(dev_info_t *dip, int (*make_ua)(dev_info_t *, char *, int))
2554 {
2555 	dev_info_t *hwdip;
2556 
2557 	ASSERT(ndi_dev_is_persistent_node(dip) == 0);
2558 	ASSERT(ddi_get_name_addr(dip) != NULL);
2559 
2560 	hwdip = ndi_devi_findchild_by_callback(ddi_get_parent(dip),
2561 	    ddi_binding_name(dip), ddi_get_name_addr(dip), make_ua);
2562 
2563 	/*
2564 	 * Look for the hardware node that is the target of the merge;
2565 	 * return failure if not found.
2566 	 */
2567 	if ((hwdip == NULL) || (hwdip == dip)) {
2568 		char *buf = kmem_alloc(MAXNAMELEN, KM_SLEEP);
2569 		NDI_CONFIG_DEBUG((CE_WARN, "No HW node to merge conf node %s",
2570 		    ddi_deviname(dip, buf)));
2571 		kmem_free(buf, MAXNAMELEN);
2572 		return (DDI_FAILURE);
2573 	}
2574 
2575 	/*
2576 	 * Make sure the hardware node is uninitialized and has no property.
2577 	 * This may not be the case if new .conf files are load after some
2578 	 * hardware nodes have already been initialized and attached.
2579 	 *
2580 	 * N.B. We return success here because the node was *intended*
2581 	 *	to be a merge node because there is a hw node with the name.
2582 	 */
2583 	mutex_enter(&DEVI(hwdip)->devi_lock);
2584 	if (ndi_dev_is_persistent_node(hwdip) == 0) {
2585 		char *buf;
2586 		mutex_exit(&DEVI(hwdip)->devi_lock);
2587 
2588 		buf = kmem_alloc(MAXNAMELEN, KM_SLEEP);
2589 		NDI_CONFIG_DEBUG((CE_NOTE, "Duplicate .conf node %s",
2590 		    ddi_deviname(dip, buf)));
2591 		kmem_free(buf, MAXNAMELEN);
2592 		return (DDI_SUCCESS);
2593 	}
2594 
2595 	/*
2596 	 * If it is possible that the hardware has already been touched
2597 	 * then don't merge.
2598 	 */
2599 	if (i_ddi_node_state(hwdip) >= DS_INITIALIZED ||
2600 	    (DEVI(hwdip)->devi_sys_prop_ptr != NULL) ||
2601 	    (DEVI(hwdip)->devi_drv_prop_ptr != NULL)) {
2602 		char *buf;
2603 		mutex_exit(&DEVI(hwdip)->devi_lock);
2604 
2605 		buf = kmem_alloc(MAXNAMELEN, KM_SLEEP);
2606 		NDI_CONFIG_DEBUG((CE_NOTE,
2607 		    "!Cannot merge .conf node %s with hw node %p "
2608 		    "-- not in proper state",
2609 		    ddi_deviname(dip, buf), (void *)hwdip));
2610 		kmem_free(buf, MAXNAMELEN);
2611 		return (DDI_SUCCESS);
2612 	}
2613 
2614 	mutex_enter(&DEVI(dip)->devi_lock);
2615 	DEVI(hwdip)->devi_sys_prop_ptr = DEVI(dip)->devi_sys_prop_ptr;
2616 	DEVI(hwdip)->devi_drv_prop_ptr = DEVI(dip)->devi_drv_prop_ptr;
2617 	DEVI(dip)->devi_sys_prop_ptr = NULL;
2618 	DEVI(dip)->devi_drv_prop_ptr = NULL;
2619 	mutex_exit(&DEVI(dip)->devi_lock);
2620 	mutex_exit(&DEVI(hwdip)->devi_lock);
2621 
2622 	return (DDI_SUCCESS);
2623 }
2624 
2625 /*
2626  * Merge a "wildcard" .conf node. This is called by nexus drivers to
2627  * augment a set of hw node with properties specified in driver.conf file.
2628  * The parent node must be held busy.
2629  *
2630  * There is no failure mode, since the nexus may or may not have child
2631  * node bound the driver specified by the wildcard node.
2632  */
2633 void
2634 ndi_merge_wildcard_node(dev_info_t *dip)
2635 {
2636 	dev_info_t *hwdip;
2637 	dev_info_t *pdip = ddi_get_parent(dip);
2638 	major_t major = ddi_driver_major(dip);
2639 
2640 	/* never attempt to merge a hw node */
2641 	ASSERT(ndi_dev_is_persistent_node(dip) == 0);
2642 	/* must be bound to a driver major number */
2643 	ASSERT(major != DDI_MAJOR_T_NONE);
2644 
2645 	/*
2646 	 * Walk the child list to find all nodes bound to major
2647 	 * and copy properties.
2648 	 */
2649 	mutex_enter(&DEVI(dip)->devi_lock);
2650 	ASSERT(DEVI_BUSY_OWNED(pdip));
2651 	for (hwdip = ddi_get_child(pdip); hwdip;
2652 	    hwdip = ddi_get_next_sibling(hwdip)) {
2653 		/*
2654 		 * Skip nodes not bound to same driver
2655 		 */
2656 		if (ddi_driver_major(hwdip) != major)
2657 			continue;
2658 
2659 		/*
2660 		 * Skip .conf nodes
2661 		 */
2662 		if (ndi_dev_is_persistent_node(hwdip) == 0)
2663 			continue;
2664 
2665 		/*
2666 		 * Make sure the node is uninitialized and has no property.
2667 		 */
2668 		mutex_enter(&DEVI(hwdip)->devi_lock);
2669 		if (i_ddi_node_state(hwdip) >= DS_INITIALIZED ||
2670 		    (DEVI(hwdip)->devi_sys_prop_ptr != NULL) ||
2671 		    (DEVI(hwdip)->devi_drv_prop_ptr != NULL)) {
2672 			mutex_exit(&DEVI(hwdip)->devi_lock);
2673 			NDI_CONFIG_DEBUG((CE_NOTE, "HW node %p state not "
2674 			    "suitable for merging wildcard conf node %s",
2675 			    (void *)hwdip, ddi_node_name(dip)));
2676 			continue;
2677 		}
2678 
2679 		DEVI(hwdip)->devi_sys_prop_ptr =
2680 		    i_ddi_prop_list_dup(DEVI(dip)->devi_sys_prop_ptr, KM_SLEEP);
2681 		DEVI(hwdip)->devi_drv_prop_ptr =
2682 		    i_ddi_prop_list_dup(DEVI(dip)->devi_drv_prop_ptr, KM_SLEEP);
2683 		mutex_exit(&DEVI(hwdip)->devi_lock);
2684 	}
2685 	mutex_exit(&DEVI(dip)->devi_lock);
2686 }
2687 
2688 /*
2689  * Return the major number based on the compatible property. This interface
2690  * may be used in situations where we are trying to detect if a better driver
2691  * now exists for a device, so it must use the 'compatible' property.  If
2692  * a non-NULL formp is specified and the binding was based on compatible then
2693  * return the pointer to the form used in *formp.
2694  */
2695 major_t
2696 ddi_compatible_driver_major(dev_info_t *dip, char **formp)
2697 {
2698 	struct dev_info *devi = DEVI(dip);
2699 	void		*compat;
2700 	size_t		len;
2701 	char		*p = NULL;
2702 	major_t		major = DDI_MAJOR_T_NONE;
2703 
2704 	if (formp)
2705 		*formp = NULL;
2706 
2707 	/*
2708 	 * Highest precedence binding is a path-oriented alias. Since this
2709 	 * requires a 'path', this type of binding occurs via more obtuse
2710 	 * 'rebind'. The need for a path-oriented alias 'rebind' is detected
2711 	 * after a successful DDI_CTLOPS_INITCHILD to another driver: this is
2712 	 * is the first point at which the unit-address (or instance) of the
2713 	 * last component of the path is available (even though the path is
2714 	 * bound to the wrong driver at this point).
2715 	 */
2716 	if (devi->devi_flags & DEVI_REBIND) {
2717 		p = devi->devi_rebinding_name;
2718 		major = ddi_name_to_major(p);
2719 		if ((major != DDI_MAJOR_T_NONE) &&
2720 		    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED)) {
2721 			if (formp)
2722 				*formp = p;
2723 			return (major);
2724 		}
2725 
2726 		/*
2727 		 * If for some reason devi_rebinding_name no longer resolves
2728 		 * to a proper driver then clear DEVI_REBIND.
2729 		 */
2730 		mutex_enter(&devi->devi_lock);
2731 		devi->devi_flags &= ~DEVI_REBIND;
2732 		mutex_exit(&devi->devi_lock);
2733 	}
2734 
2735 	/* look up compatible property */
2736 	(void) lookup_compatible(dip, KM_SLEEP);
2737 	compat = (void *)(devi->devi_compat_names);
2738 	len = devi->devi_compat_length;
2739 
2740 	/* find the highest precedence compatible form with a driver binding */
2741 	while ((p = prom_decode_composite_string(compat, len, p)) != NULL) {
2742 		major = ddi_name_to_major(p);
2743 		if ((major != DDI_MAJOR_T_NONE) &&
2744 		    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED)) {
2745 			if (formp)
2746 				*formp = p;
2747 			return (major);
2748 		}
2749 	}
2750 
2751 	/*
2752 	 * none of the compatible forms have a driver binding, see if
2753 	 * the node name has a driver binding.
2754 	 */
2755 	major = ddi_name_to_major(ddi_node_name(dip));
2756 	if ((major != DDI_MAJOR_T_NONE) &&
2757 	    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED))
2758 		return (major);
2759 
2760 	/* no driver */
2761 	return (DDI_MAJOR_T_NONE);
2762 }
2763 
2764 /*
2765  * Static help functions
2766  */
2767 
2768 /*
2769  * lookup the "compatible" property and cache it's contents in the
2770  * device node.
2771  */
2772 static int
2773 lookup_compatible(dev_info_t *dip, uint_t flag)
2774 {
2775 	int rv;
2776 	int prop_flags;
2777 	uint_t ncompatstrs;
2778 	char **compatstrpp;
2779 	char *di_compat_strp;
2780 	size_t di_compat_strlen;
2781 
2782 	if (DEVI(dip)->devi_compat_names) {
2783 		return (DDI_SUCCESS);
2784 	}
2785 
2786 	prop_flags = DDI_PROP_TYPE_STRING | DDI_PROP_DONTPASS;
2787 
2788 	if (flag & KM_NOSLEEP) {
2789 		prop_flags |= DDI_PROP_DONTSLEEP;
2790 	}
2791 
2792 	if (ndi_dev_is_prom_node(dip) == 0) {
2793 		prop_flags |= DDI_PROP_NOTPROM;
2794 	}
2795 
2796 	rv = ddi_prop_lookup_common(DDI_DEV_T_ANY, dip, prop_flags,
2797 	    "compatible", &compatstrpp, &ncompatstrs,
2798 	    ddi_prop_fm_decode_strings);
2799 
2800 	if (rv == DDI_PROP_NOT_FOUND) {
2801 		return (DDI_SUCCESS);
2802 	}
2803 
2804 	if (rv != DDI_PROP_SUCCESS) {
2805 		return (DDI_FAILURE);
2806 	}
2807 
2808 	/*
2809 	 * encode the compatible property data in the dev_info node
2810 	 */
2811 	rv = DDI_SUCCESS;
2812 	if (ncompatstrs != 0) {
2813 		di_compat_strp = encode_composite_string(compatstrpp,
2814 		    ncompatstrs, &di_compat_strlen, flag);
2815 		if (di_compat_strp != NULL) {
2816 			DEVI(dip)->devi_compat_names = di_compat_strp;
2817 			DEVI(dip)->devi_compat_length = di_compat_strlen;
2818 		} else {
2819 			rv = DDI_FAILURE;
2820 		}
2821 	}
2822 	ddi_prop_free(compatstrpp);
2823 	return (rv);
2824 }
2825 
2826 /*
2827  * Create a composite string from a list of strings.
2828  *
2829  * A composite string consists of a single buffer containing one
2830  * or more NULL terminated strings.
2831  */
2832 static char *
2833 encode_composite_string(char **strings, uint_t nstrings, size_t *retsz,
2834     uint_t flag)
2835 {
2836 	uint_t index;
2837 	char  **strpp;
2838 	uint_t slen;
2839 	size_t cbuf_sz = 0;
2840 	char *cbuf_p;
2841 	char *cbuf_ip;
2842 
2843 	if (strings == NULL || nstrings == 0 || retsz == NULL) {
2844 		return (NULL);
2845 	}
2846 
2847 	for (index = 0, strpp = strings; index < nstrings; index++)
2848 		cbuf_sz += strlen(*(strpp++)) + 1;
2849 
2850 	if ((cbuf_p = kmem_alloc(cbuf_sz, flag)) == NULL) {
2851 		cmn_err(CE_NOTE,
2852 		    "?failed to allocate device node compatstr");
2853 		return (NULL);
2854 	}
2855 
2856 	cbuf_ip = cbuf_p;
2857 	for (index = 0, strpp = strings; index < nstrings; index++) {
2858 		slen = strlen(*strpp);
2859 		bcopy(*(strpp++), cbuf_ip, slen);
2860 		cbuf_ip += slen;
2861 		*(cbuf_ip++) = '\0';
2862 	}
2863 
2864 	*retsz = cbuf_sz;
2865 	return (cbuf_p);
2866 }
2867 
2868 static void
2869 link_to_driver_list(dev_info_t *dip)
2870 {
2871 	major_t major = DEVI(dip)->devi_major;
2872 	struct devnames *dnp;
2873 
2874 	ASSERT(major != DDI_MAJOR_T_NONE);
2875 
2876 	/*
2877 	 * Remove from orphan list
2878 	 */
2879 	if (ndi_dev_is_persistent_node(dip)) {
2880 		dnp = &orphanlist;
2881 		remove_from_dn_list(dnp, dip);
2882 	}
2883 
2884 	/*
2885 	 * Add to per driver list
2886 	 */
2887 	dnp = &devnamesp[major];
2888 	add_to_dn_list(dnp, dip);
2889 }
2890 
2891 static void
2892 unlink_from_driver_list(dev_info_t *dip)
2893 {
2894 	major_t major = DEVI(dip)->devi_major;
2895 	struct devnames *dnp;
2896 
2897 	ASSERT(major != DDI_MAJOR_T_NONE);
2898 
2899 	/*
2900 	 * Remove from per-driver list
2901 	 */
2902 	dnp = &devnamesp[major];
2903 	remove_from_dn_list(dnp, dip);
2904 
2905 	/*
2906 	 * Add to orphan list
2907 	 */
2908 	if (ndi_dev_is_persistent_node(dip)) {
2909 		dnp = &orphanlist;
2910 		add_to_dn_list(dnp, dip);
2911 	}
2912 }
2913 
2914 /*
2915  * scan the per-driver list looking for dev_info "dip"
2916  */
2917 static dev_info_t *
2918 in_dn_list(struct devnames *dnp, dev_info_t *dip)
2919 {
2920 	struct dev_info *idevi;
2921 
2922 	if ((idevi = DEVI(dnp->dn_head)) == NULL)
2923 		return (NULL);
2924 
2925 	while (idevi) {
2926 		if (idevi == DEVI(dip))
2927 			return (dip);
2928 		idevi = idevi->devi_next;
2929 	}
2930 	return (NULL);
2931 }
2932 
2933 /*
2934  * insert devinfo node 'dip' into the per-driver instance list
2935  * headed by 'dnp'
2936  *
2937  * Nodes on the per-driver list are ordered: HW - SID - PSEUDO.  The order is
2938  * required for merging of .conf file data to work properly.
2939  */
2940 static void
2941 add_to_ordered_dn_list(struct devnames *dnp, dev_info_t *dip)
2942 {
2943 	dev_info_t **dipp;
2944 
2945 	ASSERT(mutex_owned(&(dnp->dn_lock)));
2946 
2947 	dipp = &dnp->dn_head;
2948 	if (ndi_dev_is_prom_node(dip)) {
2949 		/*
2950 		 * Find the first non-prom node or end of list
2951 		 */
2952 		while (*dipp && (ndi_dev_is_prom_node(*dipp) != 0)) {
2953 			dipp = (dev_info_t **)&DEVI(*dipp)->devi_next;
2954 		}
2955 	} else if (ndi_dev_is_persistent_node(dip)) {
2956 		/*
2957 		 * Find the first non-persistent node
2958 		 */
2959 		while (*dipp && (ndi_dev_is_persistent_node(*dipp) != 0)) {
2960 			dipp = (dev_info_t **)&DEVI(*dipp)->devi_next;
2961 		}
2962 	} else {
2963 		/*
2964 		 * Find the end of the list
2965 		 */
2966 		while (*dipp) {
2967 			dipp = (dev_info_t **)&DEVI(*dipp)->devi_next;
2968 		}
2969 	}
2970 
2971 	DEVI(dip)->devi_next = DEVI(*dipp);
2972 	*dipp = dip;
2973 }
2974 
2975 /*
2976  * add a list of device nodes to the device node list in the
2977  * devnames structure
2978  */
2979 static void
2980 add_to_dn_list(struct devnames *dnp, dev_info_t *dip)
2981 {
2982 	/*
2983 	 * Look to see if node already exists
2984 	 */
2985 	LOCK_DEV_OPS(&(dnp->dn_lock));
2986 	if (in_dn_list(dnp, dip)) {
2987 		cmn_err(CE_NOTE, "add_to_dn_list: node %s already in list",
2988 		    DEVI(dip)->devi_node_name);
2989 	} else {
2990 		add_to_ordered_dn_list(dnp, dip);
2991 	}
2992 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
2993 }
2994 
2995 static void
2996 remove_from_dn_list(struct devnames *dnp, dev_info_t *dip)
2997 {
2998 	dev_info_t **plist;
2999 
3000 	LOCK_DEV_OPS(&(dnp->dn_lock));
3001 
3002 	plist = (dev_info_t **)&dnp->dn_head;
3003 	while (*plist && (*plist != dip)) {
3004 		plist = (dev_info_t **)&DEVI(*plist)->devi_next;
3005 	}
3006 
3007 	if (*plist != NULL) {
3008 		ASSERT(*plist == dip);
3009 		*plist = (dev_info_t *)(DEVI(dip)->devi_next);
3010 		DEVI(dip)->devi_next = NULL;
3011 	} else {
3012 		NDI_CONFIG_DEBUG((CE_NOTE,
3013 		    "remove_from_dn_list: node %s not found in list",
3014 		    DEVI(dip)->devi_node_name));
3015 	}
3016 
3017 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
3018 }
3019 
3020 /*
3021  * Add and remove reference driver global property list
3022  */
3023 static void
3024 add_global_props(dev_info_t *dip)
3025 {
3026 	struct devnames *dnp;
3027 	ddi_prop_list_t *plist;
3028 
3029 	ASSERT(DEVI(dip)->devi_global_prop_list == NULL);
3030 	ASSERT(DEVI(dip)->devi_major != DDI_MAJOR_T_NONE);
3031 
3032 	dnp = &devnamesp[DEVI(dip)->devi_major];
3033 	LOCK_DEV_OPS(&dnp->dn_lock);
3034 	plist = dnp->dn_global_prop_ptr;
3035 	if (plist == NULL) {
3036 		UNLOCK_DEV_OPS(&dnp->dn_lock);
3037 		return;
3038 	}
3039 	i_ddi_prop_list_hold(plist, dnp);
3040 	UNLOCK_DEV_OPS(&dnp->dn_lock);
3041 
3042 	mutex_enter(&DEVI(dip)->devi_lock);
3043 	DEVI(dip)->devi_global_prop_list = plist;
3044 	mutex_exit(&DEVI(dip)->devi_lock);
3045 }
3046 
3047 static void
3048 remove_global_props(dev_info_t *dip)
3049 {
3050 	ddi_prop_list_t *proplist;
3051 
3052 	mutex_enter(&DEVI(dip)->devi_lock);
3053 	proplist = DEVI(dip)->devi_global_prop_list;
3054 	DEVI(dip)->devi_global_prop_list = NULL;
3055 	mutex_exit(&DEVI(dip)->devi_lock);
3056 
3057 	if (proplist) {
3058 		major_t major;
3059 		struct devnames *dnp;
3060 
3061 		major = ddi_driver_major(dip);
3062 		ASSERT(major != DDI_MAJOR_T_NONE);
3063 		dnp = &devnamesp[major];
3064 		LOCK_DEV_OPS(&dnp->dn_lock);
3065 		i_ddi_prop_list_rele(proplist, dnp);
3066 		UNLOCK_DEV_OPS(&dnp->dn_lock);
3067 	}
3068 }
3069 
3070 #ifdef DEBUG
3071 /*
3072  * Set this variable to '0' to disable the optimization,
3073  * and to 2 to print debug message.
3074  */
3075 static int optimize_dtree = 1;
3076 
3077 static void
3078 debug_dtree(dev_info_t *devi, struct dev_info *adevi, char *service)
3079 {
3080 	char *adeviname, *buf;
3081 
3082 	/*
3083 	 * Don't print unless optimize dtree is set to 2+
3084 	 */
3085 	if (optimize_dtree <= 1)
3086 		return;
3087 
3088 	buf = kmem_alloc(MAXNAMELEN, KM_SLEEP);
3089 	adeviname = ddi_deviname((dev_info_t *)adevi, buf);
3090 	if (*adeviname == '\0')
3091 		adeviname = "root";
3092 
3093 	cmn_err(CE_CONT, "%s %s -> %s\n",
3094 	    ddi_deviname(devi, buf), service, adeviname);
3095 
3096 	kmem_free(buf, MAXNAMELEN);
3097 }
3098 #else /* DEBUG */
3099 #define	debug_dtree(a1, a2, a3)	 /* nothing */
3100 #endif  /* DEBUG */
3101 
3102 static void
3103 ddi_optimize_dtree(dev_info_t *devi)
3104 {
3105 	struct dev_info *pdevi;
3106 	struct bus_ops *b;
3107 
3108 	pdevi = DEVI(devi)->devi_parent;
3109 	ASSERT(pdevi);
3110 
3111 	/*
3112 	 * Set the unoptimized values
3113 	 */
3114 	DEVI(devi)->devi_bus_map_fault = pdevi;
3115 	DEVI(devi)->devi_bus_dma_map = pdevi;
3116 	DEVI(devi)->devi_bus_dma_allochdl = pdevi;
3117 	DEVI(devi)->devi_bus_dma_freehdl = pdevi;
3118 	DEVI(devi)->devi_bus_dma_bindhdl = pdevi;
3119 	DEVI(devi)->devi_bus_dma_bindfunc =
3120 	    pdevi->devi_ops->devo_bus_ops->bus_dma_bindhdl;
3121 	DEVI(devi)->devi_bus_dma_unbindhdl = pdevi;
3122 	DEVI(devi)->devi_bus_dma_unbindfunc =
3123 	    pdevi->devi_ops->devo_bus_ops->bus_dma_unbindhdl;
3124 	DEVI(devi)->devi_bus_dma_flush = pdevi;
3125 	DEVI(devi)->devi_bus_dma_win = pdevi;
3126 	DEVI(devi)->devi_bus_dma_ctl = pdevi;
3127 	DEVI(devi)->devi_bus_ctl = pdevi;
3128 
3129 #ifdef DEBUG
3130 	if (optimize_dtree == 0)
3131 		return;
3132 #endif /* DEBUG */
3133 
3134 	b = pdevi->devi_ops->devo_bus_ops;
3135 
3136 	if (i_ddi_map_fault == b->bus_map_fault) {
3137 		DEVI(devi)->devi_bus_map_fault = pdevi->devi_bus_map_fault;
3138 		debug_dtree(devi, DEVI(devi)->devi_bus_map_fault,
3139 		    "bus_map_fault");
3140 	}
3141 
3142 	if (ddi_dma_map == b->bus_dma_map) {
3143 		DEVI(devi)->devi_bus_dma_map = pdevi->devi_bus_dma_map;
3144 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_map, "bus_dma_map");
3145 	}
3146 
3147 	if (ddi_dma_allochdl == b->bus_dma_allochdl) {
3148 		DEVI(devi)->devi_bus_dma_allochdl =
3149 		    pdevi->devi_bus_dma_allochdl;
3150 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_allochdl,
3151 		    "bus_dma_allochdl");
3152 	}
3153 
3154 	if (ddi_dma_freehdl == b->bus_dma_freehdl) {
3155 		DEVI(devi)->devi_bus_dma_freehdl = pdevi->devi_bus_dma_freehdl;
3156 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_freehdl,
3157 		    "bus_dma_freehdl");
3158 	}
3159 
3160 	if (ddi_dma_bindhdl == b->bus_dma_bindhdl) {
3161 		DEVI(devi)->devi_bus_dma_bindhdl = pdevi->devi_bus_dma_bindhdl;
3162 		DEVI(devi)->devi_bus_dma_bindfunc =
3163 		    pdevi->devi_bus_dma_bindhdl->devi_ops->
3164 		    devo_bus_ops->bus_dma_bindhdl;
3165 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_bindhdl,
3166 		    "bus_dma_bindhdl");
3167 	}
3168 
3169 	if (ddi_dma_unbindhdl == b->bus_dma_unbindhdl) {
3170 		DEVI(devi)->devi_bus_dma_unbindhdl =
3171 		    pdevi->devi_bus_dma_unbindhdl;
3172 		DEVI(devi)->devi_bus_dma_unbindfunc =
3173 		    pdevi->devi_bus_dma_unbindhdl->devi_ops->
3174 		    devo_bus_ops->bus_dma_unbindhdl;
3175 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_unbindhdl,
3176 		    "bus_dma_unbindhdl");
3177 	}
3178 
3179 	if (ddi_dma_flush == b->bus_dma_flush) {
3180 		DEVI(devi)->devi_bus_dma_flush = pdevi->devi_bus_dma_flush;
3181 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_flush,
3182 		    "bus_dma_flush");
3183 	}
3184 
3185 	if (ddi_dma_win == b->bus_dma_win) {
3186 		DEVI(devi)->devi_bus_dma_win = pdevi->devi_bus_dma_win;
3187 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_win,
3188 		    "bus_dma_win");
3189 	}
3190 
3191 	if (ddi_dma_mctl == b->bus_dma_ctl) {
3192 		DEVI(devi)->devi_bus_dma_ctl = pdevi->devi_bus_dma_ctl;
3193 		debug_dtree(devi, DEVI(devi)->devi_bus_dma_ctl, "bus_dma_ctl");
3194 	}
3195 
3196 	if (ddi_ctlops == b->bus_ctl) {
3197 		DEVI(devi)->devi_bus_ctl = pdevi->devi_bus_ctl;
3198 		debug_dtree(devi, DEVI(devi)->devi_bus_ctl, "bus_ctl");
3199 	}
3200 }
3201 
3202 #define	MIN_DEVINFO_LOG_SIZE	max_ncpus
3203 #define	MAX_DEVINFO_LOG_SIZE	max_ncpus * 10
3204 
3205 static void
3206 da_log_init()
3207 {
3208 	devinfo_log_header_t *dh;
3209 	int logsize = devinfo_log_size;
3210 
3211 	if (logsize == 0)
3212 		logsize = MIN_DEVINFO_LOG_SIZE;
3213 	else if (logsize > MAX_DEVINFO_LOG_SIZE)
3214 		logsize = MAX_DEVINFO_LOG_SIZE;
3215 
3216 	dh = kmem_alloc(logsize * PAGESIZE, KM_SLEEP);
3217 	mutex_init(&dh->dh_lock, NULL, MUTEX_DEFAULT, NULL);
3218 	dh->dh_max = ((logsize * PAGESIZE) - sizeof (*dh)) /
3219 	    sizeof (devinfo_audit_t) + 1;
3220 	dh->dh_curr = -1;
3221 	dh->dh_hits = 0;
3222 
3223 	devinfo_audit_log = dh;
3224 }
3225 
3226 /*
3227  * Log the stack trace in per-devinfo audit structure and also enter
3228  * it into a system wide log for recording the time history.
3229  */
3230 static void
3231 da_log_enter(dev_info_t *dip)
3232 {
3233 	devinfo_audit_t *da_log, *da = DEVI(dip)->devi_audit;
3234 	devinfo_log_header_t *dh = devinfo_audit_log;
3235 
3236 	if (devinfo_audit_log == NULL)
3237 		return;
3238 
3239 	ASSERT(da != NULL);
3240 
3241 	da->da_devinfo = dip;
3242 	da->da_timestamp = gethrtime();
3243 	da->da_thread = curthread;
3244 	da->da_node_state = DEVI(dip)->devi_node_state;
3245 	da->da_device_state = DEVI(dip)->devi_state;
3246 	da->da_depth = getpcstack(da->da_stack, DDI_STACK_DEPTH);
3247 
3248 	/*
3249 	 * Copy into common log and note the location for tracing history
3250 	 */
3251 	mutex_enter(&dh->dh_lock);
3252 	dh->dh_hits++;
3253 	dh->dh_curr++;
3254 	if (dh->dh_curr >= dh->dh_max)
3255 		dh->dh_curr -= dh->dh_max;
3256 	da_log = &dh->dh_entry[dh->dh_curr];
3257 	mutex_exit(&dh->dh_lock);
3258 
3259 	bcopy(da, da_log, sizeof (devinfo_audit_t));
3260 	da->da_lastlog = da_log;
3261 }
3262 
3263 static void
3264 attach_drivers()
3265 {
3266 	int i;
3267 	for (i = 0; i < devcnt; i++) {
3268 		struct devnames *dnp = &devnamesp[i];
3269 		if ((dnp->dn_flags & DN_FORCE_ATTACH) &&
3270 		    (ddi_hold_installed_driver((major_t)i) != NULL))
3271 			ddi_rele_driver((major_t)i);
3272 	}
3273 }
3274 
3275 /*
3276  * Launch a thread to force attach drivers. This avoids penalty on boot time.
3277  */
3278 void
3279 i_ddi_forceattach_drivers()
3280 {
3281 	/*
3282 	 * On i386, the USB drivers need to load and take over from the
3283 	 * SMM BIOS drivers ASAP after consconfig(), so make sure they
3284 	 * get loaded right here rather than letting the thread do it.
3285 	 *
3286 	 * The order here is important.  EHCI must be loaded first, as
3287 	 * we have observed many systems on which hangs occur if the
3288 	 * {U,O}HCI companion controllers take over control from the BIOS
3289 	 * before EHCI does.  These hangs are also caused by BIOSes leaving
3290 	 * interrupt-on-port-change enabled in the ehci controller, so that
3291 	 * when uhci/ohci reset themselves, it induces a port change on
3292 	 * the ehci companion controller.  Since there's no interrupt handler
3293 	 * installed at the time, the moment that interrupt is unmasked, an
3294 	 * interrupt storm will occur.  All this is averted when ehci is
3295 	 * loaded first.  And now you know..... the REST of the story.
3296 	 *
3297 	 * Regardless of platform, ehci needs to initialize first to avoid
3298 	 * unnecessary connects and disconnects on the companion controller
3299 	 * when ehci sets up the routing.
3300 	 */
3301 	(void) ddi_hold_installed_driver(ddi_name_to_major("ehci"));
3302 	(void) ddi_hold_installed_driver(ddi_name_to_major("uhci"));
3303 	(void) ddi_hold_installed_driver(ddi_name_to_major("ohci"));
3304 
3305 	/*
3306 	 * Attach IB VHCI driver before the force-attach thread attaches the
3307 	 * IB HCA driver. IB HCA driver will fail if IB Nexus has not yet
3308 	 * been attached.
3309 	 */
3310 	(void) ddi_hold_installed_driver(ddi_name_to_major("ib"));
3311 
3312 	(void) thread_create(NULL, 0, (void (*)())attach_drivers, NULL, 0, &p0,
3313 	    TS_RUN, minclsyspri);
3314 }
3315 
3316 /*
3317  * This is a private DDI interface for optimizing boot performance.
3318  * I/O subsystem initialization is considered complete when devfsadm
3319  * is executed.
3320  *
3321  * NOTE: The start of syseventd happens to be a convenient indicator
3322  *	of the completion of I/O initialization during boot.
3323  *	The implementation should be replaced by something more robust.
3324  */
3325 int
3326 i_ddi_io_initialized()
3327 {
3328 	extern int sysevent_daemon_init;
3329 	return (sysevent_daemon_init);
3330 }
3331 
3332 /*
3333  * May be used to determine system boot state
3334  * "Available" means the system is for the most part up
3335  * and initialized, with all system services either up or
3336  * capable of being started.  This state is set by devfsadm
3337  * during the boot process.  The /dev filesystem infers
3338  * from this when implicit reconfig can be performed,
3339  * ie, devfsadm can be invoked.  Please avoid making
3340  * further use of this unless it's really necessary.
3341  */
3342 int
3343 i_ddi_sysavail()
3344 {
3345 	return (devname_state & DS_SYSAVAIL);
3346 }
3347 
3348 /*
3349  * May be used to determine if boot is a reconfigure boot.
3350  */
3351 int
3352 i_ddi_reconfig()
3353 {
3354 	return (devname_state & DS_RECONFIG);
3355 }
3356 
3357 /*
3358  * Note system services are up, inform /dev.
3359  */
3360 void
3361 i_ddi_set_sysavail()
3362 {
3363 	if ((devname_state & DS_SYSAVAIL) == 0) {
3364 		devname_state |= DS_SYSAVAIL;
3365 		sdev_devstate_change();
3366 	}
3367 }
3368 
3369 /*
3370  * Note reconfiguration boot, inform /dev.
3371  */
3372 void
3373 i_ddi_set_reconfig()
3374 {
3375 	if ((devname_state & DS_RECONFIG) == 0) {
3376 		devname_state |= DS_RECONFIG;
3377 		sdev_devstate_change();
3378 	}
3379 }
3380 
3381 
3382 /*
3383  * device tree walking
3384  */
3385 
3386 struct walk_elem {
3387 	struct walk_elem *next;
3388 	dev_info_t *dip;
3389 };
3390 
3391 static void
3392 free_list(struct walk_elem *list)
3393 {
3394 	while (list) {
3395 		struct walk_elem *next = list->next;
3396 		kmem_free(list, sizeof (*list));
3397 		list = next;
3398 	}
3399 }
3400 
3401 static void
3402 append_node(struct walk_elem **list, dev_info_t *dip)
3403 {
3404 	struct walk_elem *tail;
3405 	struct walk_elem *elem = kmem_alloc(sizeof (*elem), KM_SLEEP);
3406 
3407 	elem->next = NULL;
3408 	elem->dip = dip;
3409 
3410 	if (*list == NULL) {
3411 		*list = elem;
3412 		return;
3413 	}
3414 
3415 	tail = *list;
3416 	while (tail->next)
3417 		tail = tail->next;
3418 
3419 	tail->next = elem;
3420 }
3421 
3422 /*
3423  * The implementation of ddi_walk_devs().
3424  */
3425 static int
3426 walk_devs(dev_info_t *dip, int (*f)(dev_info_t *, void *), void *arg,
3427     int do_locking)
3428 {
3429 	struct walk_elem *head = NULL;
3430 
3431 	/*
3432 	 * Do it in two passes. First pass invoke callback on each
3433 	 * dip on the sibling list. Second pass invoke callback on
3434 	 * children of each dip.
3435 	 */
3436 	while (dip) {
3437 		switch ((*f)(dip, arg)) {
3438 		case DDI_WALK_TERMINATE:
3439 			free_list(head);
3440 			return (DDI_WALK_TERMINATE);
3441 
3442 		case DDI_WALK_PRUNESIB:
3443 			/* ignore sibling by setting dip to NULL */
3444 			append_node(&head, dip);
3445 			dip = NULL;
3446 			break;
3447 
3448 		case DDI_WALK_PRUNECHILD:
3449 			/* don't worry about children */
3450 			dip = ddi_get_next_sibling(dip);
3451 			break;
3452 
3453 		case DDI_WALK_CONTINUE:
3454 		default:
3455 			append_node(&head, dip);
3456 			dip = ddi_get_next_sibling(dip);
3457 			break;
3458 		}
3459 
3460 	}
3461 
3462 	/* second pass */
3463 	while (head) {
3464 		int circ;
3465 		struct walk_elem *next = head->next;
3466 
3467 		if (do_locking)
3468 			ndi_devi_enter(head->dip, &circ);
3469 		if (walk_devs(ddi_get_child(head->dip), f, arg, do_locking) ==
3470 		    DDI_WALK_TERMINATE) {
3471 			if (do_locking)
3472 				ndi_devi_exit(head->dip, circ);
3473 			free_list(head);
3474 			return (DDI_WALK_TERMINATE);
3475 		}
3476 		if (do_locking)
3477 			ndi_devi_exit(head->dip, circ);
3478 		kmem_free(head, sizeof (*head));
3479 		head = next;
3480 	}
3481 
3482 	return (DDI_WALK_CONTINUE);
3483 }
3484 
3485 /*
3486  * This general-purpose routine traverses the tree of dev_info nodes,
3487  * starting from the given node, and calls the given function for each
3488  * node that it finds with the current node and the pointer arg (which
3489  * can point to a structure of information that the function
3490  * needs) as arguments.
3491  *
3492  * It does the walk a layer at a time, not depth-first. The given function
3493  * must return one of the following values:
3494  *	DDI_WALK_CONTINUE
3495  *	DDI_WALK_PRUNESIB
3496  *	DDI_WALK_PRUNECHILD
3497  *	DDI_WALK_TERMINATE
3498  *
3499  * N.B. Since we walk the sibling list, the caller must ensure that
3500  *	the parent of dip is held against changes, unless the parent
3501  *	is rootnode.  ndi_devi_enter() on the parent is sufficient.
3502  *
3503  *	To avoid deadlock situations, caller must not attempt to
3504  *	configure/unconfigure/remove device node in (*f)(), nor should
3505  *	it attempt to recurse on other nodes in the system. Any
3506  *	ndi_devi_enter() done by (*f)() must occur 'at-or-below' the
3507  *	node entered prior to ddi_walk_devs(). Furthermore, if (*f)()
3508  *	does any multi-threading (in framework *or* in driver) then the
3509  *	ndi_devi_enter() calls done by dependent threads must be
3510  *	'strictly-below'.
3511  *
3512  *	This is not callable from device autoconfiguration routines.
3513  *	They include, but not limited to, _init(9e), _fini(9e), probe(9e),
3514  *	attach(9e), and detach(9e).
3515  */
3516 
3517 void
3518 ddi_walk_devs(dev_info_t *dip, int (*f)(dev_info_t *, void *), void *arg)
3519 {
3520 
3521 	ASSERT(dip == NULL || ddi_get_parent(dip) == NULL ||
3522 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
3523 
3524 	(void) walk_devs(dip, f, arg, 1);
3525 }
3526 
3527 /*
3528  * This is a general-purpose routine traverses the per-driver list
3529  * and calls the given function for each node. must return one of
3530  * the following values:
3531  *	DDI_WALK_CONTINUE
3532  *	DDI_WALK_TERMINATE
3533  *
3534  * N.B. The same restrictions from ddi_walk_devs() apply.
3535  */
3536 
3537 void
3538 e_ddi_walk_driver(char *drv, int (*f)(dev_info_t *, void *), void *arg)
3539 {
3540 	major_t major;
3541 	struct devnames *dnp;
3542 	dev_info_t *dip;
3543 
3544 	major = ddi_name_to_major(drv);
3545 	if (major == DDI_MAJOR_T_NONE)
3546 		return;
3547 
3548 	dnp = &devnamesp[major];
3549 	LOCK_DEV_OPS(&dnp->dn_lock);
3550 	dip = dnp->dn_head;
3551 	while (dip) {
3552 		ndi_hold_devi(dip);
3553 		UNLOCK_DEV_OPS(&dnp->dn_lock);
3554 		if ((*f)(dip, arg) == DDI_WALK_TERMINATE) {
3555 			ndi_rele_devi(dip);
3556 			return;
3557 		}
3558 		LOCK_DEV_OPS(&dnp->dn_lock);
3559 		ndi_rele_devi(dip);
3560 		dip = ddi_get_next(dip);
3561 	}
3562 	UNLOCK_DEV_OPS(&dnp->dn_lock);
3563 }
3564 
3565 /*
3566  * argument to i_find_devi, a devinfo node search callback function.
3567  */
3568 struct match_info {
3569 	dev_info_t	*dip;		/* result */
3570 	char		*nodename;	/* if non-null, nodename must match */
3571 	int		instance;	/* if != -1, instance must match */
3572 	int		attached;	/* if != 0, i_ddi_devi_attached() */
3573 };
3574 
3575 static int
3576 i_find_devi(dev_info_t *dip, void *arg)
3577 {
3578 	struct match_info *info = (struct match_info *)arg;
3579 
3580 	if (((info->nodename == NULL) ||
3581 	    (strcmp(ddi_node_name(dip), info->nodename) == 0)) &&
3582 	    ((info->instance == -1) ||
3583 	    (ddi_get_instance(dip) == info->instance)) &&
3584 	    ((info->attached == 0) || i_ddi_devi_attached(dip))) {
3585 		info->dip = dip;
3586 		ndi_hold_devi(dip);
3587 		return (DDI_WALK_TERMINATE);
3588 	}
3589 
3590 	return (DDI_WALK_CONTINUE);
3591 }
3592 
3593 /*
3594  * Find dip with a known node name and instance and return with it held
3595  */
3596 dev_info_t *
3597 ddi_find_devinfo(char *nodename, int instance, int attached)
3598 {
3599 	struct match_info	info;
3600 
3601 	info.nodename = nodename;
3602 	info.instance = instance;
3603 	info.attached = attached;
3604 	info.dip = NULL;
3605 
3606 	ddi_walk_devs(ddi_root_node(), i_find_devi, &info);
3607 	return (info.dip);
3608 }
3609 
3610 /*
3611  * Parse for name, addr, and minor names. Some args may be NULL.
3612  */
3613 void
3614 i_ddi_parse_name(char *name, char **nodename, char **addrname, char **minorname)
3615 {
3616 	char *cp;
3617 	static char nulladdrname[] = "";
3618 
3619 	/* default values */
3620 	if (nodename)
3621 		*nodename = name;
3622 	if (addrname)
3623 		*addrname = nulladdrname;
3624 	if (minorname)
3625 		*minorname = NULL;
3626 
3627 	cp = name;
3628 	while (*cp != '\0') {
3629 		if (addrname && *cp == '@') {
3630 			*addrname = cp + 1;
3631 			*cp = '\0';
3632 		} else if (minorname && *cp == ':') {
3633 			*minorname = cp + 1;
3634 			*cp = '\0';
3635 		}
3636 		++cp;
3637 	}
3638 }
3639 
3640 static char *
3641 child_path_to_driver(dev_info_t *parent, char *child_name, char *unit_address)
3642 {
3643 	char *p, *drvname = NULL;
3644 	major_t maj;
3645 
3646 	/*
3647 	 * Construct the pathname and ask the implementation
3648 	 * if it can do a driver = f(pathname) for us, if not
3649 	 * we'll just default to using the node-name that
3650 	 * was given to us.  We want to do this first to
3651 	 * allow the platform to use 'generic' names for
3652 	 * legacy device drivers.
3653 	 */
3654 	p = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
3655 	(void) ddi_pathname(parent, p);
3656 	(void) strcat(p, "/");
3657 	(void) strcat(p, child_name);
3658 	if (unit_address && *unit_address) {
3659 		(void) strcat(p, "@");
3660 		(void) strcat(p, unit_address);
3661 	}
3662 
3663 	/*
3664 	 * Get the binding. If there is none, return the child_name
3665 	 * and let the caller deal with it.
3666 	 */
3667 	maj = path_to_major(p);
3668 
3669 	kmem_free(p, MAXPATHLEN);
3670 
3671 	if (maj != DDI_MAJOR_T_NONE)
3672 		drvname = ddi_major_to_name(maj);
3673 	if (drvname == NULL)
3674 		drvname = child_name;
3675 
3676 	return (drvname);
3677 }
3678 
3679 
3680 #define	PCI_EX_CLASS	"pciexclass"
3681 #define	PCI_EX		"pciex"
3682 #define	PCI_CLASS	"pciclass"
3683 #define	PCI		"pci"
3684 
3685 int
3686 ddi_is_pci_dip(dev_info_t *dip)
3687 {
3688 	char	*prop = NULL;
3689 
3690 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
3691 	    "compatible", &prop) == DDI_PROP_SUCCESS) {
3692 		ASSERT(prop);
3693 		if (strncmp(prop, PCI_EX_CLASS, sizeof (PCI_EX_CLASS) - 1)
3694 		    == 0 ||
3695 		    strncmp(prop, PCI_EX, sizeof (PCI_EX)- 1)
3696 		    == 0 ||
3697 		    strncmp(prop, PCI_CLASS, sizeof (PCI_CLASS) - 1)
3698 		    == 0 ||
3699 		    strncmp(prop, PCI, sizeof (PCI) - 1)
3700 		    == 0) {
3701 			ddi_prop_free(prop);
3702 			return (1);
3703 		}
3704 	}
3705 
3706 	if (prop != NULL) {
3707 		ddi_prop_free(prop);
3708 	}
3709 
3710 	return (0);
3711 }
3712 
3713 /*
3714  * Given the pathname of a device, fill in the dev_info_t value and/or the
3715  * dev_t value and/or the spectype, depending on which parameters are non-NULL.
3716  * If there is an error, this function returns -1.
3717  *
3718  * NOTE: If this function returns the dev_info_t structure, then it
3719  * does so with a hold on the devi. Caller should ensure that they get
3720  * decremented via ddi_release_devi() or ndi_rele_devi();
3721  *
3722  * This function can be invoked in the boot case for a pathname without
3723  * device argument (:xxxx), traditionally treated as a minor name.
3724  * In this case, we do the following
3725  * (1) search the minor node of type DDM_DEFAULT.
3726  * (2) if no DDM_DEFAULT minor exists, then the first non-alias minor is chosen.
3727  * (3) if neither exists, a dev_t is faked with minor number = instance.
3728  * As of S9 FCS, no instance of #1 exists. #2 is used by several platforms
3729  * to default the boot partition to :a possibly by other OBP definitions.
3730  * #3 is used for booting off network interfaces, most SPARC network
3731  * drivers support Style-2 only, so only DDM_ALIAS minor exists.
3732  *
3733  * It is possible for OBP to present device args at the end of the path as
3734  * well as in the middle. For example, with IB the following strings are
3735  * valid boot paths.
3736  *	a /pci@8,700000/ib@1,2:port=1,pkey=ff,dhcp,...
3737  *	b /pci@8,700000/ib@1,1:port=1/ioc@xxxxxx,yyyyyyy:dhcp
3738  * Case (a), we first look for minor node "port=1,pkey...".
3739  * Failing that, we will pass "port=1,pkey..." to the bus_config
3740  * entry point of ib (HCA) driver.
3741  * Case (b), configure ib@1,1 as usual. Then invoke ib's bus_config
3742  * with argument "ioc@xxxxxxx,yyyyyyy:port=1". After configuring
3743  * the ioc, look for minor node dhcp. If not found, pass ":dhcp"
3744  * to ioc's bus_config entry point.
3745  */
3746 int
3747 resolve_pathname(char *pathname,
3748 	dev_info_t **dipp, dev_t *devtp, int *spectypep)
3749 {
3750 	int			error;
3751 	dev_info_t		*parent, *child;
3752 	struct pathname		pn;
3753 	char			*component, *config_name;
3754 	char			*minorname = NULL;
3755 	char			*prev_minor = NULL;
3756 	dev_t			devt = NODEV;
3757 	int			spectype;
3758 	struct ddi_minor_data	*dmn;
3759 	int			circ;
3760 
3761 	if (*pathname != '/')
3762 		return (EINVAL);
3763 	parent = ddi_root_node();	/* Begin at the top of the tree */
3764 
3765 	if (error = pn_get(pathname, UIO_SYSSPACE, &pn))
3766 		return (error);
3767 	pn_skipslash(&pn);
3768 
3769 	ASSERT(i_ddi_devi_attached(parent));
3770 	ndi_hold_devi(parent);
3771 
3772 	component = kmem_alloc(MAXNAMELEN, KM_SLEEP);
3773 	config_name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
3774 
3775 	while (pn_pathleft(&pn)) {
3776 		/* remember prev minor (:xxx) in the middle of path */
3777 		if (minorname)
3778 			prev_minor = i_ddi_strdup(minorname, KM_SLEEP);
3779 
3780 		/* Get component and chop off minorname */
3781 		(void) pn_getcomponent(&pn, component);
3782 		i_ddi_parse_name(component, NULL, NULL, &minorname);
3783 
3784 		if (prev_minor == NULL) {
3785 			(void) snprintf(config_name, MAXNAMELEN, "%s",
3786 			    component);
3787 		} else {
3788 			(void) snprintf(config_name, MAXNAMELEN, "%s:%s",
3789 			    component, prev_minor);
3790 			kmem_free(prev_minor, strlen(prev_minor) + 1);
3791 			prev_minor = NULL;
3792 		}
3793 
3794 		/*
3795 		 * Find and configure the child
3796 		 */
3797 		if (ndi_devi_config_one(parent, config_name, &child,
3798 		    NDI_PROMNAME | NDI_NO_EVENT) != NDI_SUCCESS) {
3799 			ndi_rele_devi(parent);
3800 			pn_free(&pn);
3801 			kmem_free(component, MAXNAMELEN);
3802 			kmem_free(config_name, MAXNAMELEN);
3803 			return (-1);
3804 		}
3805 
3806 		ASSERT(i_ddi_devi_attached(child));
3807 		ndi_rele_devi(parent);
3808 		parent = child;
3809 		pn_skipslash(&pn);
3810 	}
3811 
3812 	/*
3813 	 * First look for a minor node matching minorname.
3814 	 * Failing that, try to pass minorname to bus_config().
3815 	 */
3816 	if (minorname && i_ddi_minorname_to_devtspectype(parent,
3817 	    minorname, &devt, &spectype) == DDI_FAILURE) {
3818 		(void) snprintf(config_name, MAXNAMELEN, "%s", minorname);
3819 		if (ndi_devi_config_obp_args(parent,
3820 		    config_name, &child, 0) != NDI_SUCCESS) {
3821 			ndi_rele_devi(parent);
3822 			pn_free(&pn);
3823 			kmem_free(component, MAXNAMELEN);
3824 			kmem_free(config_name, MAXNAMELEN);
3825 			NDI_CONFIG_DEBUG((CE_NOTE,
3826 			    "%s: minor node not found\n", pathname));
3827 			return (-1);
3828 		}
3829 		minorname = NULL;	/* look for default minor */
3830 		ASSERT(i_ddi_devi_attached(child));
3831 		ndi_rele_devi(parent);
3832 		parent = child;
3833 	}
3834 
3835 	if (devtp || spectypep) {
3836 		if (minorname == NULL) {
3837 			/*
3838 			 * Search for a default entry with an active
3839 			 * ndi_devi_enter to protect the devi_minor list.
3840 			 */
3841 			ndi_devi_enter(parent, &circ);
3842 			for (dmn = DEVI(parent)->devi_minor; dmn;
3843 			    dmn = dmn->next) {
3844 				if (dmn->type == DDM_DEFAULT) {
3845 					devt = dmn->ddm_dev;
3846 					spectype = dmn->ddm_spec_type;
3847 					break;
3848 				}
3849 			}
3850 
3851 			if (devt == NODEV) {
3852 				/*
3853 				 * No default minor node, try the first one;
3854 				 * else, assume 1-1 instance-minor mapping
3855 				 */
3856 				dmn = DEVI(parent)->devi_minor;
3857 				if (dmn && ((dmn->type == DDM_MINOR) ||
3858 				    (dmn->type == DDM_INTERNAL_PATH))) {
3859 					devt = dmn->ddm_dev;
3860 					spectype = dmn->ddm_spec_type;
3861 				} else {
3862 					devt = makedevice(
3863 					    DEVI(parent)->devi_major,
3864 					    ddi_get_instance(parent));
3865 					spectype = S_IFCHR;
3866 				}
3867 			}
3868 			ndi_devi_exit(parent, circ);
3869 		}
3870 		if (devtp)
3871 			*devtp = devt;
3872 		if (spectypep)
3873 			*spectypep = spectype;
3874 	}
3875 
3876 	pn_free(&pn);
3877 	kmem_free(component, MAXNAMELEN);
3878 	kmem_free(config_name, MAXNAMELEN);
3879 
3880 	/*
3881 	 * If there is no error, return the appropriate parameters
3882 	 */
3883 	if (dipp != NULL)
3884 		*dipp = parent;
3885 	else {
3886 		/*
3887 		 * We should really keep the ref count to keep the node from
3888 		 * detaching but ddi_pathname_to_dev_t() specifies a NULL dipp,
3889 		 * so we have no way of passing back the held dip.  Not holding
3890 		 * the dip allows detaches to occur - which can cause problems
3891 		 * for subsystems which call ddi_pathname_to_dev_t (console).
3892 		 *
3893 		 * Instead of holding the dip, we place a ddi-no-autodetach
3894 		 * property on the node to prevent auto detaching.
3895 		 *
3896 		 * The right fix is to remove ddi_pathname_to_dev_t and replace
3897 		 * it, and all references, with a call that specifies a dipp.
3898 		 * In addition, the callers of this new interfaces would then
3899 		 * need to call ndi_rele_devi when the reference is complete.
3900 		 *
3901 		 */
3902 		(void) ddi_prop_update_int(DDI_DEV_T_NONE, parent,
3903 		    DDI_NO_AUTODETACH, 1);
3904 		ndi_rele_devi(parent);
3905 	}
3906 
3907 	return (0);
3908 }
3909 
3910 /*
3911  * Given the pathname of a device, return the dev_t of the corresponding
3912  * device.  Returns NODEV on failure.
3913  *
3914  * Note that this call sets the DDI_NO_AUTODETACH property on the devinfo node.
3915  */
3916 dev_t
3917 ddi_pathname_to_dev_t(char *pathname)
3918 {
3919 	dev_t devt;
3920 	int error;
3921 
3922 	error = resolve_pathname(pathname, NULL, &devt, NULL);
3923 
3924 	return (error ? NODEV : devt);
3925 }
3926 
3927 /*
3928  * Translate a prom pathname to kernel devfs pathname.
3929  * Caller is assumed to allocate devfspath memory of
3930  * size at least MAXPATHLEN
3931  *
3932  * The prom pathname may not include minor name, but
3933  * devfs pathname has a minor name portion.
3934  */
3935 int
3936 i_ddi_prompath_to_devfspath(char *prompath, char *devfspath)
3937 {
3938 	dev_t		devt = (dev_t)NODEV;
3939 	dev_info_t	*dip = NULL;
3940 	char		*minor_name = NULL;
3941 	int		spectype;
3942 	int		error;
3943 	int		circ;
3944 
3945 	error = resolve_pathname(prompath, &dip, &devt, &spectype);
3946 	if (error)
3947 		return (DDI_FAILURE);
3948 	ASSERT(dip && devt != NODEV);
3949 
3950 	/*
3951 	 * Get in-kernel devfs pathname
3952 	 */
3953 	(void) ddi_pathname(dip, devfspath);
3954 
3955 	ndi_devi_enter(dip, &circ);
3956 	minor_name = i_ddi_devtspectype_to_minorname(dip, devt, spectype);
3957 	if (minor_name) {
3958 		(void) strcat(devfspath, ":");
3959 		(void) strcat(devfspath, minor_name);
3960 	} else {
3961 		/*
3962 		 * If minor_name is NULL, we have an alias minor node.
3963 		 * So manufacture a path to the corresponding clone minor.
3964 		 */
3965 		(void) snprintf(devfspath, MAXPATHLEN, "%s:%s",
3966 		    CLONE_PATH, ddi_driver_name(dip));
3967 	}
3968 	ndi_devi_exit(dip, circ);
3969 
3970 	/* release hold from resolve_pathname() */
3971 	ndi_rele_devi(dip);
3972 	return (0);
3973 }
3974 
3975 /*
3976  * This function is intended to identify drivers that must quiesce for fast
3977  * reboot to succeed.  It does not claim to have more knowledge about the device
3978  * than its driver.  If a driver has implemented quiesce(), it will be invoked;
3979  * if a so identified driver does not manage any device that needs to be
3980  * quiesced, it must explicitly set its devo_quiesce dev_op to
3981  * ddi_quiesce_not_needed.
3982  */
3983 static int skip_pseudo = 1;	/* Skip pseudo devices */
3984 static int skip_non_hw = 1;	/* Skip devices with no hardware property */
3985 static int
3986 should_implement_quiesce(dev_info_t *dip)
3987 {
3988 	struct dev_info *devi = DEVI(dip);
3989 	dev_info_t *pdip;
3990 
3991 	/*
3992 	 * If dip is pseudo and skip_pseudo is set, driver doesn't have to
3993 	 * implement quiesce().
3994 	 */
3995 	if (skip_pseudo &&
3996 	    strncmp(ddi_binding_name(dip), "pseudo", sizeof ("pseudo")) == 0)
3997 		return (0);
3998 
3999 	/*
4000 	 * If parent dip is pseudo and skip_pseudo is set, driver doesn't have
4001 	 * to implement quiesce().
4002 	 */
4003 	if (skip_pseudo && (pdip = ddi_get_parent(dip)) != NULL &&
4004 	    strncmp(ddi_binding_name(pdip), "pseudo", sizeof ("pseudo")) == 0)
4005 		return (0);
4006 
4007 	/*
4008 	 * If not attached, driver doesn't have to implement quiesce().
4009 	 */
4010 	if (!i_ddi_devi_attached(dip))
4011 		return (0);
4012 
4013 	/*
4014 	 * If dip has no hardware property and skip_non_hw is set,
4015 	 * driver doesn't have to implement quiesce().
4016 	 */
4017 	if (skip_non_hw && devi->devi_hw_prop_ptr == NULL)
4018 		return (0);
4019 
4020 	return (1);
4021 }
4022 
4023 static int
4024 driver_has_quiesce(struct dev_ops *ops)
4025 {
4026 	if ((ops->devo_rev >= 4) && (ops->devo_quiesce != nodev) &&
4027 	    (ops->devo_quiesce != NULL) && (ops->devo_quiesce != nulldev) &&
4028 	    (ops->devo_quiesce != ddi_quiesce_not_supported))
4029 		return (1);
4030 	else
4031 		return (0);
4032 }
4033 
4034 /*
4035  * Check to see if a driver has implemented the quiesce() DDI function.
4036  */
4037 int
4038 check_driver_quiesce(dev_info_t *dip, void *arg)
4039 {
4040 	struct dev_ops *ops;
4041 
4042 	if (!should_implement_quiesce(dip))
4043 		return (DDI_WALK_CONTINUE);
4044 
4045 	if ((ops = ddi_get_driver(dip)) == NULL)
4046 		return (DDI_WALK_CONTINUE);
4047 
4048 	if (driver_has_quiesce(ops)) {
4049 		if ((quiesce_debug & 0x2) == 0x2) {
4050 			if (ops->devo_quiesce == ddi_quiesce_not_needed)
4051 				cmn_err(CE_CONT, "%s does not need to be "
4052 				    "quiesced", ddi_driver_name(dip));
4053 			else
4054 				cmn_err(CE_CONT, "%s has quiesce routine",
4055 				    ddi_driver_name(dip));
4056 		}
4057 	} else {
4058 		if (arg != NULL)
4059 			*((int *)arg) = -1;
4060 		cmn_err(CE_WARN, "%s has no quiesce()", ddi_driver_name(dip));
4061 	}
4062 
4063 	return (DDI_WALK_CONTINUE);
4064 }
4065 
4066 /*
4067  * Quiesce device.
4068  */
4069 static void
4070 quiesce_one_device(dev_info_t *dip, void *arg)
4071 {
4072 	struct dev_ops *ops;
4073 	int should_quiesce = 0;
4074 
4075 	/*
4076 	 * If the device is not attached it doesn't need to be quiesced.
4077 	 */
4078 	if (!i_ddi_devi_attached(dip))
4079 		return;
4080 
4081 	if ((ops = ddi_get_driver(dip)) == NULL)
4082 		return;
4083 
4084 	should_quiesce = should_implement_quiesce(dip);
4085 
4086 	/*
4087 	 * If there's an implementation of quiesce(), always call it even if
4088 	 * some of the drivers don't have quiesce() or quiesce() have failed
4089 	 * so we can do force fast reboot.  The implementation of quiesce()
4090 	 * should not negatively affect a regular reboot.
4091 	 */
4092 	if (driver_has_quiesce(ops)) {
4093 		int rc = DDI_SUCCESS;
4094 
4095 		if (ops->devo_quiesce == ddi_quiesce_not_needed)
4096 			return;
4097 
4098 		rc = devi_quiesce(dip);
4099 
4100 		/* quiesce() should never fail */
4101 		ASSERT(rc == DDI_SUCCESS);
4102 
4103 		if (rc != DDI_SUCCESS && should_quiesce) {
4104 
4105 			if (arg != NULL)
4106 				*((int *)arg) = -1;
4107 		}
4108 	} else if (should_quiesce && arg != NULL) {
4109 		*((int *)arg) = -1;
4110 	}
4111 }
4112 
4113 /*
4114  * Traverse the dev info tree in a breadth-first manner so that we quiesce
4115  * children first.  All subtrees under the parent of dip will be quiesced.
4116  */
4117 void
4118 quiesce_devices(dev_info_t *dip, void *arg)
4119 {
4120 	/*
4121 	 * if we're reached here, the device tree better not be changing.
4122 	 * so either devinfo_freeze better be set or we better be panicing.
4123 	 */
4124 	ASSERT(devinfo_freeze || panicstr);
4125 
4126 	for (; dip != NULL; dip = ddi_get_next_sibling(dip)) {
4127 		quiesce_devices(ddi_get_child(dip), arg);
4128 
4129 		quiesce_one_device(dip, arg);
4130 	}
4131 }
4132 
4133 /*
4134  * Reset all the pure leaf drivers on the system at halt time
4135  */
4136 static int
4137 reset_leaf_device(dev_info_t *dip, void *arg)
4138 {
4139 	_NOTE(ARGUNUSED(arg))
4140 	struct dev_ops *ops;
4141 
4142 	/* if the device doesn't need to be reset then there's nothing to do */
4143 	if (!DEVI_NEED_RESET(dip))
4144 		return (DDI_WALK_CONTINUE);
4145 
4146 	/*
4147 	 * if the device isn't a char/block device or doesn't have a
4148 	 * reset entry point then there's nothing to do.
4149 	 */
4150 	ops = ddi_get_driver(dip);
4151 	if ((ops == NULL) || (ops->devo_cb_ops == NULL) ||
4152 	    (ops->devo_reset == nodev) || (ops->devo_reset == nulldev) ||
4153 	    (ops->devo_reset == NULL))
4154 		return (DDI_WALK_CONTINUE);
4155 
4156 	if (DEVI_IS_ATTACHING(dip) || DEVI_IS_DETACHING(dip)) {
4157 		static char path[MAXPATHLEN];
4158 
4159 		/*
4160 		 * bad news, this device has blocked in it's attach or
4161 		 * detach routine, which means it not safe to call it's
4162 		 * devo_reset() entry point.
4163 		 */
4164 		cmn_err(CE_WARN, "unable to reset device: %s",
4165 		    ddi_pathname(dip, path));
4166 		return (DDI_WALK_CONTINUE);
4167 	}
4168 
4169 	NDI_CONFIG_DEBUG((CE_NOTE, "resetting %s%d\n",
4170 	    ddi_driver_name(dip), ddi_get_instance(dip)));
4171 
4172 	(void) devi_reset(dip, DDI_RESET_FORCE);
4173 	return (DDI_WALK_CONTINUE);
4174 }
4175 
4176 void
4177 reset_leaves(void)
4178 {
4179 	/*
4180 	 * if we're reached here, the device tree better not be changing.
4181 	 * so either devinfo_freeze better be set or we better be panicing.
4182 	 */
4183 	ASSERT(devinfo_freeze || panicstr);
4184 
4185 	(void) walk_devs(top_devinfo, reset_leaf_device, NULL, 0);
4186 }
4187 
4188 
4189 /*
4190  * devtree_freeze() must be called before quiesce_devices() and reset_leaves()
4191  * during a normal system shutdown.  It attempts to ensure that there are no
4192  * outstanding attach or detach operations in progress when quiesce_devices() or
4193  * reset_leaves()is invoked.  It must be called before the system becomes
4194  * single-threaded because device attach and detach are multi-threaded
4195  * operations.  (note that during system shutdown the system doesn't actually
4196  * become single-thread since other threads still exist, but the shutdown thread
4197  * will disable preemption for itself, raise it's pil, and stop all the other
4198  * cpus in the system there by effectively making the system single-threaded.)
4199  */
4200 void
4201 devtree_freeze(void)
4202 {
4203 	int delayed = 0;
4204 
4205 	/* if we're panicing then the device tree isn't going to be changing */
4206 	if (panicstr)
4207 		return;
4208 
4209 	/* stop all dev_info state changes in the device tree */
4210 	devinfo_freeze = gethrtime();
4211 
4212 	/*
4213 	 * if we're not panicing and there are on-going attach or detach
4214 	 * operations, wait for up to 3 seconds for them to finish.  This
4215 	 * is a randomly chosen interval but this should be ok because:
4216 	 * - 3 seconds is very small relative to the deadman timer.
4217 	 * - normal attach and detach operations should be very quick.
4218 	 * - attach and detach operations are fairly rare.
4219 	 */
4220 	while (!panicstr && atomic_add_long_nv(&devinfo_attach_detach, 0) &&
4221 	    (delayed < 3)) {
4222 		delayed += 1;
4223 
4224 		/* do a sleeping wait for one second */
4225 		ASSERT(!servicing_interrupt());
4226 		delay(drv_usectohz(MICROSEC));
4227 	}
4228 }
4229 
4230 static int
4231 bind_dip(dev_info_t *dip, void *arg)
4232 {
4233 	_NOTE(ARGUNUSED(arg))
4234 	char	*path;
4235 	major_t	major, pmajor;
4236 
4237 	/*
4238 	 * If the node is currently bound to the wrong driver, try to unbind
4239 	 * so that we can rebind to the correct driver.
4240 	 */
4241 	if (i_ddi_node_state(dip) >= DS_BOUND) {
4242 		major = ddi_compatible_driver_major(dip, NULL);
4243 		if ((DEVI(dip)->devi_major == major) &&
4244 		    (i_ddi_node_state(dip) >= DS_INITIALIZED)) {
4245 			/*
4246 			 * Check for a path-oriented driver alias that
4247 			 * takes precedence over current driver binding.
4248 			 */
4249 			path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4250 			(void) ddi_pathname(dip, path);
4251 			pmajor = ddi_name_to_major(path);
4252 			if ((pmajor != DDI_MAJOR_T_NONE) &&
4253 			    !(devnamesp[pmajor].dn_flags & DN_DRIVER_REMOVED))
4254 				major = pmajor;
4255 			kmem_free(path, MAXPATHLEN);
4256 		}
4257 
4258 		/* attempt unbind if current driver is incorrect */
4259 		if ((major != DDI_MAJOR_T_NONE) &&
4260 		    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED) &&
4261 		    (major != DEVI(dip)->devi_major))
4262 			(void) ndi_devi_unbind_driver(dip);
4263 	}
4264 
4265 	/* If unbound, try to bind to a driver */
4266 	if (i_ddi_node_state(dip) < DS_BOUND)
4267 		(void) ndi_devi_bind_driver(dip, 0);
4268 
4269 	return (DDI_WALK_CONTINUE);
4270 }
4271 
4272 void
4273 i_ddi_bind_devs(void)
4274 {
4275 	/* flush devfs so that ndi_devi_unbind_driver will work when possible */
4276 	(void) devfs_clean(top_devinfo, NULL, 0);
4277 
4278 	ddi_walk_devs(top_devinfo, bind_dip, (void *)NULL);
4279 }
4280 
4281 /* callback data for unbind_children_by_alias() */
4282 typedef struct unbind_data {
4283 	major_t	drv_major;
4284 	char	*drv_alias;
4285 	int	ndevs_bound;
4286 	int	unbind_errors;
4287 } unbind_data_t;
4288 
4289 /*
4290  * A utility function provided for testing and support convenience
4291  * Called for each device during an upgrade_drv -d bound to the alias
4292  * that cannot be unbound due to device in use.
4293  */
4294 static void
4295 unbind_alias_dev_in_use(dev_info_t *dip, char *alias)
4296 {
4297 	if (moddebug & MODDEBUG_BINDING) {
4298 		cmn_err(CE_CONT, "%s%d: state %d: bound to %s\n",
4299 		    ddi_driver_name(dip), ddi_get_instance(dip),
4300 		    i_ddi_node_state(dip), alias);
4301 	}
4302 }
4303 
4304 /*
4305  * walkdevs callback for unbind devices bound to specific driver
4306  * and alias.  Invoked within the context of update_drv -d <alias>.
4307  */
4308 static int
4309 unbind_children_by_alias(dev_info_t *dip, void *arg)
4310 {
4311 	int		circ;
4312 	dev_info_t	*cdip;
4313 	dev_info_t	*next;
4314 	unbind_data_t	*ub = (unbind_data_t *)(uintptr_t)arg;
4315 	int		rv;
4316 
4317 	/*
4318 	 * We are called from update_drv to try to unbind a specific
4319 	 * set of aliases for a driver.  Unbind what persistent nodes
4320 	 * we can, and return the number of nodes which cannot be unbound.
4321 	 * If not all nodes can be unbound, update_drv leaves the
4322 	 * state of the driver binding files unchanged, except in
4323 	 * the case of -f.
4324 	 */
4325 	ndi_devi_enter(dip, &circ);
4326 	for (cdip = ddi_get_child(dip); cdip; cdip = next) {
4327 		next = ddi_get_next_sibling(cdip);
4328 		if ((ddi_driver_major(cdip) != ub->drv_major) ||
4329 		    (strcmp(DEVI(cdip)->devi_node_name, ub->drv_alias) != 0))
4330 			continue;
4331 		if (i_ddi_node_state(cdip) >= DS_BOUND) {
4332 			rv = ndi_devi_unbind_driver(cdip);
4333 			if (rv != DDI_SUCCESS ||
4334 			    (i_ddi_node_state(cdip) >= DS_BOUND)) {
4335 				unbind_alias_dev_in_use(cdip, ub->drv_alias);
4336 				ub->ndevs_bound++;
4337 				continue;
4338 			}
4339 			if (ndi_dev_is_persistent_node(cdip) == 0)
4340 				(void) ddi_remove_child(cdip, 0);
4341 		}
4342 	}
4343 	ndi_devi_exit(dip, circ);
4344 
4345 	return (DDI_WALK_CONTINUE);
4346 }
4347 
4348 /*
4349  * Unbind devices by driver & alias
4350  * Context: update_drv [-f] -d -i <alias> <driver>
4351  */
4352 int
4353 i_ddi_unbind_devs_by_alias(major_t major, char *alias)
4354 {
4355 	unbind_data_t	*ub;
4356 	int		rv;
4357 
4358 	ub = kmem_zalloc(sizeof (*ub), KM_SLEEP);
4359 	ub->drv_major = major;
4360 	ub->drv_alias = alias;
4361 	ub->ndevs_bound = 0;
4362 	ub->unbind_errors = 0;
4363 
4364 	/* flush devfs so that ndi_devi_unbind_driver will work when possible */
4365 	devfs_clean(top_devinfo, NULL, 0);
4366 	ddi_walk_devs(top_devinfo, unbind_children_by_alias,
4367 	    (void *)(uintptr_t)ub);
4368 
4369 	/* return the number of devices remaining bound to the alias */
4370 	rv = ub->ndevs_bound + ub->unbind_errors;
4371 	kmem_free(ub, sizeof (*ub));
4372 	return (rv);
4373 }
4374 
4375 /*
4376  * walkdevs callback for unbind devices by driver
4377  */
4378 static int
4379 unbind_children_by_driver(dev_info_t *dip, void *arg)
4380 {
4381 	int		circ;
4382 	dev_info_t	*cdip;
4383 	dev_info_t	*next;
4384 	major_t		major = (major_t)(uintptr_t)arg;
4385 	int		rv;
4386 
4387 	/*
4388 	 * We are called either from rem_drv or update_drv when reloading
4389 	 * a driver.conf file. In either case, we unbind persistent nodes
4390 	 * and destroy .conf nodes. In the case of rem_drv, this will be
4391 	 * the final state. In the case of update_drv,  i_ddi_bind_devs()
4392 	 * may be invoked later to re-enumerate (new) driver.conf rebind
4393 	 * persistent nodes.
4394 	 */
4395 	ndi_devi_enter(dip, &circ);
4396 	for (cdip = ddi_get_child(dip); cdip; cdip = next) {
4397 		next = ddi_get_next_sibling(cdip);
4398 		if (ddi_driver_major(cdip) != major)
4399 			continue;
4400 		if (i_ddi_node_state(cdip) >= DS_BOUND) {
4401 			rv = ndi_devi_unbind_driver(cdip);
4402 			if (rv == DDI_FAILURE ||
4403 			    (i_ddi_node_state(cdip) >= DS_BOUND))
4404 				continue;
4405 			if (ndi_dev_is_persistent_node(cdip) == 0)
4406 				(void) ddi_remove_child(cdip, 0);
4407 		}
4408 	}
4409 	ndi_devi_exit(dip, circ);
4410 
4411 	return (DDI_WALK_CONTINUE);
4412 }
4413 
4414 /*
4415  * Unbind devices by driver
4416  * Context: rem_drv or unload driver.conf
4417  */
4418 void
4419 i_ddi_unbind_devs(major_t major)
4420 {
4421 	/* flush devfs so that ndi_devi_unbind_driver will work when possible */
4422 	devfs_clean(top_devinfo, NULL, 0);
4423 	ddi_walk_devs(top_devinfo, unbind_children_by_driver,
4424 	    (void *)(uintptr_t)major);
4425 }
4426 
4427 /*
4428  * I/O Hotplug control
4429  */
4430 
4431 /*
4432  * create and attach a dev_info node from a .conf file spec
4433  */
4434 static void
4435 init_spec_child(dev_info_t *pdip, struct hwc_spec *specp, uint_t flags)
4436 {
4437 	_NOTE(ARGUNUSED(flags))
4438 	dev_info_t *dip;
4439 	char *node_name;
4440 
4441 	if (((node_name = specp->hwc_devi_name) == NULL) ||
4442 	    (ddi_name_to_major(node_name) == DDI_MAJOR_T_NONE)) {
4443 		char *tmp = node_name;
4444 		if (tmp == NULL)
4445 			tmp = "<none>";
4446 		cmn_err(CE_CONT,
4447 		    "init_spec_child: parent=%s, bad spec (%s)\n",
4448 		    ddi_node_name(pdip), tmp);
4449 		return;
4450 	}
4451 
4452 	dip = i_ddi_alloc_node(pdip, node_name, (pnode_t)DEVI_PSEUDO_NODEID,
4453 	    -1, specp->hwc_devi_sys_prop_ptr, KM_SLEEP);
4454 
4455 	if (dip == NULL)
4456 		return;
4457 
4458 	if (ddi_initchild(pdip, dip) != DDI_SUCCESS)
4459 		(void) ddi_remove_child(dip, 0);
4460 }
4461 
4462 /*
4463  * Lookup hwc specs from hash tables and make children from the spec
4464  * Because some .conf children are "merge" nodes, we also initialize
4465  * .conf children to merge properties onto hardware nodes.
4466  *
4467  * The pdip must be held busy.
4468  */
4469 int
4470 i_ndi_make_spec_children(dev_info_t *pdip, uint_t flags)
4471 {
4472 	extern struct hwc_spec *hwc_get_child_spec(dev_info_t *, major_t);
4473 	int			circ;
4474 	struct hwc_spec		*list, *spec;
4475 
4476 	ndi_devi_enter(pdip, &circ);
4477 	if (DEVI(pdip)->devi_flags & DEVI_MADE_CHILDREN) {
4478 		ndi_devi_exit(pdip, circ);
4479 		return (DDI_SUCCESS);
4480 	}
4481 
4482 	list = hwc_get_child_spec(pdip, DDI_MAJOR_T_NONE);
4483 	for (spec = list; spec != NULL; spec = spec->hwc_next) {
4484 		init_spec_child(pdip, spec, flags);
4485 	}
4486 	hwc_free_spec_list(list);
4487 
4488 	mutex_enter(&DEVI(pdip)->devi_lock);
4489 	DEVI(pdip)->devi_flags |= DEVI_MADE_CHILDREN;
4490 	mutex_exit(&DEVI(pdip)->devi_lock);
4491 	ndi_devi_exit(pdip, circ);
4492 	return (DDI_SUCCESS);
4493 }
4494 
4495 /*
4496  * Run initchild on all child nodes such that instance assignment
4497  * for multiport network cards are contiguous.
4498  *
4499  * The pdip must be held busy.
4500  */
4501 static void
4502 i_ndi_init_hw_children(dev_info_t *pdip, uint_t flags)
4503 {
4504 	dev_info_t *dip;
4505 
4506 	ASSERT(DEVI(pdip)->devi_flags & DEVI_MADE_CHILDREN);
4507 
4508 	/* contiguous instance assignment */
4509 	e_ddi_enter_instance();
4510 	dip = ddi_get_child(pdip);
4511 	while (dip) {
4512 		if (ndi_dev_is_persistent_node(dip))
4513 			(void) i_ndi_config_node(dip, DS_INITIALIZED, flags);
4514 		dip = ddi_get_next_sibling(dip);
4515 	}
4516 	e_ddi_exit_instance();
4517 }
4518 
4519 /*
4520  * report device status
4521  */
4522 static void
4523 i_ndi_devi_report_status_change(dev_info_t *dip, char *path)
4524 {
4525 	char *status;
4526 
4527 	if (!DEVI_NEED_REPORT(dip) ||
4528 	    (i_ddi_node_state(dip) < DS_INITIALIZED) ||
4529 	    ndi_dev_is_hidden_node(dip)) {
4530 		return;
4531 	}
4532 
4533 	/* Invalidate the devinfo snapshot cache */
4534 	i_ddi_di_cache_invalidate();
4535 
4536 	if (DEVI_IS_DEVICE_REMOVED(dip)) {
4537 		status = "removed";
4538 	} else if (DEVI_IS_DEVICE_OFFLINE(dip)) {
4539 		status = "offline";
4540 	} else if (DEVI_IS_DEVICE_DOWN(dip)) {
4541 		status = "down";
4542 	} else if (DEVI_IS_BUS_QUIESCED(dip)) {
4543 		status = "quiesced";
4544 	} else if (DEVI_IS_BUS_DOWN(dip)) {
4545 		status = "down";
4546 	} else if (i_ddi_devi_attached(dip)) {
4547 		status = "online";
4548 	} else {
4549 		status = "unknown";
4550 	}
4551 
4552 	if (path == NULL) {
4553 		path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4554 		cmn_err(CE_CONT, "?%s (%s%d) %s\n",
4555 		    ddi_pathname(dip, path), ddi_driver_name(dip),
4556 		    ddi_get_instance(dip), status);
4557 		kmem_free(path, MAXPATHLEN);
4558 	} else {
4559 		cmn_err(CE_CONT, "?%s (%s%d) %s\n",
4560 		    path, ddi_driver_name(dip),
4561 		    ddi_get_instance(dip), status);
4562 	}
4563 
4564 	mutex_enter(&(DEVI(dip)->devi_lock));
4565 	DEVI_REPORT_DONE(dip);
4566 	mutex_exit(&(DEVI(dip)->devi_lock));
4567 }
4568 
4569 /*
4570  * log a notification that a dev_info node has been configured.
4571  */
4572 static int
4573 i_log_devfs_add_devinfo(dev_info_t *dip, uint_t flags)
4574 {
4575 	int			se_err;
4576 	char			*pathname;
4577 	sysevent_t		*ev;
4578 	sysevent_id_t		eid;
4579 	sysevent_value_t	se_val;
4580 	sysevent_attr_list_t	*ev_attr_list = NULL;
4581 	char			*class_name;
4582 	int			no_transport = 0;
4583 
4584 	ASSERT(dip && ddi_get_parent(dip) &&
4585 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
4586 
4587 	/* do not generate ESC_DEVFS_DEVI_ADD event during boot */
4588 	if (!i_ddi_io_initialized())
4589 		return (DDI_SUCCESS);
4590 
4591 	/* Invalidate the devinfo snapshot cache */
4592 	i_ddi_di_cache_invalidate();
4593 
4594 	ev = sysevent_alloc(EC_DEVFS, ESC_DEVFS_DEVI_ADD, EP_DDI, SE_SLEEP);
4595 
4596 	pathname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4597 
4598 	(void) ddi_pathname(dip, pathname);
4599 	ASSERT(strlen(pathname));
4600 
4601 	se_val.value_type = SE_DATA_TYPE_STRING;
4602 	se_val.value.sv_string = pathname;
4603 	if (sysevent_add_attr(&ev_attr_list, DEVFS_PATHNAME,
4604 	    &se_val, SE_SLEEP) != 0) {
4605 		goto fail;
4606 	}
4607 
4608 	/* add the device class attribute */
4609 	if ((class_name = i_ddi_devi_class(dip)) != NULL) {
4610 		se_val.value_type = SE_DATA_TYPE_STRING;
4611 		se_val.value.sv_string = class_name;
4612 
4613 		if (sysevent_add_attr(&ev_attr_list,
4614 		    DEVFS_DEVI_CLASS, &se_val, SE_SLEEP) != 0) {
4615 			sysevent_free_attr(ev_attr_list);
4616 			goto fail;
4617 		}
4618 	}
4619 
4620 	/*
4621 	 * must log a branch event too unless NDI_BRANCH_EVENT_OP is set,
4622 	 * in which case the branch event will be logged by the caller
4623 	 * after the entire branch has been configured.
4624 	 */
4625 	if ((flags & NDI_BRANCH_EVENT_OP) == 0) {
4626 		/*
4627 		 * Instead of logging a separate branch event just add
4628 		 * DEVFS_BRANCH_EVENT attribute. It indicates devfsadmd to
4629 		 * generate a EC_DEV_BRANCH event.
4630 		 */
4631 		se_val.value_type = SE_DATA_TYPE_INT32;
4632 		se_val.value.sv_int32 = 1;
4633 		if (sysevent_add_attr(&ev_attr_list,
4634 		    DEVFS_BRANCH_EVENT, &se_val, SE_SLEEP) != 0) {
4635 			sysevent_free_attr(ev_attr_list);
4636 			goto fail;
4637 		}
4638 	}
4639 
4640 	if (sysevent_attach_attributes(ev, ev_attr_list) != 0) {
4641 		sysevent_free_attr(ev_attr_list);
4642 		goto fail;
4643 	}
4644 
4645 	if ((se_err = log_sysevent(ev, SE_SLEEP, &eid)) != 0) {
4646 		if (se_err == SE_NO_TRANSPORT)
4647 			no_transport = 1;
4648 		goto fail;
4649 	}
4650 
4651 	sysevent_free(ev);
4652 	kmem_free(pathname, MAXPATHLEN);
4653 
4654 	return (DDI_SUCCESS);
4655 
4656 fail:
4657 	cmn_err(CE_WARN, "failed to log ESC_DEVFS_DEVI_ADD event for %s%s",
4658 	    pathname, (no_transport) ? " (syseventd not responding)" : "");
4659 
4660 	cmn_err(CE_WARN, "/dev may not be current for driver %s. "
4661 	    "Run devfsadm -i %s",
4662 	    ddi_driver_name(dip), ddi_driver_name(dip));
4663 
4664 	sysevent_free(ev);
4665 	kmem_free(pathname, MAXPATHLEN);
4666 	return (DDI_SUCCESS);
4667 }
4668 
4669 /*
4670  * log a notification that a dev_info node has been unconfigured.
4671  */
4672 static int
4673 i_log_devfs_remove_devinfo(char *pathname, char *class_name, char *driver_name,
4674     int instance, uint_t flags)
4675 {
4676 	sysevent_t		*ev;
4677 	sysevent_id_t		eid;
4678 	sysevent_value_t	se_val;
4679 	sysevent_attr_list_t	*ev_attr_list = NULL;
4680 	int			se_err;
4681 	int			no_transport = 0;
4682 
4683 	if (!i_ddi_io_initialized())
4684 		return (DDI_SUCCESS);
4685 
4686 	/* Invalidate the devinfo snapshot cache */
4687 	i_ddi_di_cache_invalidate();
4688 
4689 	ev = sysevent_alloc(EC_DEVFS, ESC_DEVFS_DEVI_REMOVE, EP_DDI, SE_SLEEP);
4690 
4691 	se_val.value_type = SE_DATA_TYPE_STRING;
4692 	se_val.value.sv_string = pathname;
4693 	if (sysevent_add_attr(&ev_attr_list, DEVFS_PATHNAME,
4694 	    &se_val, SE_SLEEP) != 0) {
4695 		goto fail;
4696 	}
4697 
4698 	if (class_name) {
4699 		/* add the device class, driver name and instance attributes */
4700 
4701 		se_val.value_type = SE_DATA_TYPE_STRING;
4702 		se_val.value.sv_string = class_name;
4703 		if (sysevent_add_attr(&ev_attr_list,
4704 		    DEVFS_DEVI_CLASS, &se_val, SE_SLEEP) != 0) {
4705 			sysevent_free_attr(ev_attr_list);
4706 			goto fail;
4707 		}
4708 
4709 		se_val.value_type = SE_DATA_TYPE_STRING;
4710 		se_val.value.sv_string = driver_name;
4711 		if (sysevent_add_attr(&ev_attr_list,
4712 		    DEVFS_DRIVER_NAME, &se_val, SE_SLEEP) != 0) {
4713 			sysevent_free_attr(ev_attr_list);
4714 			goto fail;
4715 		}
4716 
4717 		se_val.value_type = SE_DATA_TYPE_INT32;
4718 		se_val.value.sv_int32 = instance;
4719 		if (sysevent_add_attr(&ev_attr_list,
4720 		    DEVFS_INSTANCE, &se_val, SE_SLEEP) != 0) {
4721 			sysevent_free_attr(ev_attr_list);
4722 			goto fail;
4723 		}
4724 	}
4725 
4726 	/*
4727 	 * must log a branch event too unless NDI_BRANCH_EVENT_OP is set,
4728 	 * in which case the branch event will be logged by the caller
4729 	 * after the entire branch has been unconfigured.
4730 	 */
4731 	if ((flags & NDI_BRANCH_EVENT_OP) == 0) {
4732 		/*
4733 		 * Instead of logging a separate branch event just add
4734 		 * DEVFS_BRANCH_EVENT attribute. It indicates devfsadmd to
4735 		 * generate a EC_DEV_BRANCH event.
4736 		 */
4737 		se_val.value_type = SE_DATA_TYPE_INT32;
4738 		se_val.value.sv_int32 = 1;
4739 		if (sysevent_add_attr(&ev_attr_list,
4740 		    DEVFS_BRANCH_EVENT, &se_val, SE_SLEEP) != 0) {
4741 			sysevent_free_attr(ev_attr_list);
4742 			goto fail;
4743 		}
4744 	}
4745 
4746 	if (sysevent_attach_attributes(ev, ev_attr_list) != 0) {
4747 		sysevent_free_attr(ev_attr_list);
4748 		goto fail;
4749 	}
4750 
4751 	if ((se_err = log_sysevent(ev, SE_SLEEP, &eid)) != 0) {
4752 		if (se_err == SE_NO_TRANSPORT)
4753 			no_transport = 1;
4754 		goto fail;
4755 	}
4756 
4757 	sysevent_free(ev);
4758 	return (DDI_SUCCESS);
4759 
4760 fail:
4761 	sysevent_free(ev);
4762 	cmn_err(CE_WARN, "failed to log ESC_DEVFS_DEVI_REMOVE event for %s%s",
4763 	    pathname, (no_transport) ? " (syseventd not responding)" : "");
4764 	return (DDI_SUCCESS);
4765 }
4766 
4767 static void
4768 i_ddi_log_devfs_device_remove(dev_info_t *dip)
4769 {
4770 	char	*path;
4771 
4772 	ASSERT(dip && ddi_get_parent(dip) &&
4773 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
4774 	ASSERT(DEVI_IS_DEVICE_REMOVED(dip));
4775 
4776 	ASSERT(i_ddi_node_state(dip) >= DS_INITIALIZED);
4777 	if (i_ddi_node_state(dip) < DS_INITIALIZED)
4778 		return;
4779 
4780 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4781 	(void) i_log_devfs_remove_devinfo(ddi_pathname(dip, path),
4782 	    i_ddi_devi_class(dip), (char *)ddi_driver_name(dip),
4783 	    ddi_get_instance(dip), 0);
4784 	kmem_free(path, MAXPATHLEN);
4785 }
4786 
4787 static void
4788 i_ddi_log_devfs_device_insert(dev_info_t *dip)
4789 {
4790 	ASSERT(dip && ddi_get_parent(dip) &&
4791 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
4792 	ASSERT(!DEVI_IS_DEVICE_REMOVED(dip));
4793 
4794 	(void) i_log_devfs_add_devinfo(dip, 0);
4795 }
4796 
4797 
4798 /*
4799  * log an event that a dev_info branch has been configured or unconfigured.
4800  */
4801 static int
4802 i_log_devfs_branch(char *node_path, char *subclass)
4803 {
4804 	int se_err;
4805 	sysevent_t *ev;
4806 	sysevent_id_t eid;
4807 	sysevent_value_t se_val;
4808 	sysevent_attr_list_t *ev_attr_list = NULL;
4809 	int no_transport = 0;
4810 
4811 	/* do not generate the event during boot */
4812 	if (!i_ddi_io_initialized())
4813 		return (DDI_SUCCESS);
4814 
4815 	/* Invalidate the devinfo snapshot cache */
4816 	i_ddi_di_cache_invalidate();
4817 
4818 	ev = sysevent_alloc(EC_DEVFS, subclass, EP_DDI, SE_SLEEP);
4819 
4820 	se_val.value_type = SE_DATA_TYPE_STRING;
4821 	se_val.value.sv_string = node_path;
4822 
4823 	if (sysevent_add_attr(&ev_attr_list, DEVFS_PATHNAME,
4824 	    &se_val, SE_SLEEP) != 0) {
4825 		goto fail;
4826 	}
4827 
4828 	if (sysevent_attach_attributes(ev, ev_attr_list) != 0) {
4829 		sysevent_free_attr(ev_attr_list);
4830 		goto fail;
4831 	}
4832 
4833 	if ((se_err = log_sysevent(ev, SE_SLEEP, &eid)) != 0) {
4834 		if (se_err == SE_NO_TRANSPORT)
4835 			no_transport = 1;
4836 		goto fail;
4837 	}
4838 
4839 	sysevent_free(ev);
4840 	return (DDI_SUCCESS);
4841 
4842 fail:
4843 	cmn_err(CE_WARN, "failed to log %s branch event for %s%s",
4844 	    subclass, node_path,
4845 	    (no_transport) ? " (syseventd not responding)" : "");
4846 
4847 	sysevent_free(ev);
4848 	return (DDI_FAILURE);
4849 }
4850 
4851 /*
4852  * log an event that a dev_info tree branch has been configured.
4853  */
4854 static int
4855 i_log_devfs_branch_add(dev_info_t *dip)
4856 {
4857 	char *node_path;
4858 	int rv;
4859 
4860 	node_path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4861 	(void) ddi_pathname(dip, node_path);
4862 	rv = i_log_devfs_branch(node_path, ESC_DEVFS_BRANCH_ADD);
4863 	kmem_free(node_path, MAXPATHLEN);
4864 
4865 	return (rv);
4866 }
4867 
4868 /*
4869  * log an event that a dev_info tree branch has been unconfigured.
4870  */
4871 static int
4872 i_log_devfs_branch_remove(char *node_path)
4873 {
4874 	return (i_log_devfs_branch(node_path, ESC_DEVFS_BRANCH_REMOVE));
4875 }
4876 
4877 /*
4878  * enqueue the dip's deviname on the branch event queue.
4879  */
4880 static struct brevq_node *
4881 brevq_enqueue(struct brevq_node **brevqp, dev_info_t *dip,
4882     struct brevq_node *child)
4883 {
4884 	struct brevq_node *brn;
4885 	char *deviname;
4886 
4887 	deviname = kmem_alloc(MAXNAMELEN, KM_SLEEP);
4888 	(void) ddi_deviname(dip, deviname);
4889 
4890 	brn = kmem_zalloc(sizeof (*brn), KM_SLEEP);
4891 	brn->brn_deviname = i_ddi_strdup(deviname, KM_SLEEP);
4892 	kmem_free(deviname, MAXNAMELEN);
4893 	brn->brn_child = child;
4894 	brn->brn_sibling = *brevqp;
4895 	*brevqp = brn;
4896 
4897 	return (brn);
4898 }
4899 
4900 /*
4901  * free the memory allocated for the elements on the branch event queue.
4902  */
4903 static void
4904 free_brevq(struct brevq_node *brevq)
4905 {
4906 	struct brevq_node *brn, *next_brn;
4907 
4908 	for (brn = brevq; brn != NULL; brn = next_brn) {
4909 		next_brn = brn->brn_sibling;
4910 		ASSERT(brn->brn_child == NULL);
4911 		kmem_free(brn->brn_deviname, strlen(brn->brn_deviname) + 1);
4912 		kmem_free(brn, sizeof (*brn));
4913 	}
4914 }
4915 
4916 /*
4917  * log the events queued up on the branch event queue and free the
4918  * associated memory.
4919  *
4920  * node_path must have been allocated with at least MAXPATHLEN bytes.
4921  */
4922 static void
4923 log_and_free_brevq(char *node_path, struct brevq_node *brevq)
4924 {
4925 	struct brevq_node *brn;
4926 	char *p;
4927 
4928 	p = node_path + strlen(node_path);
4929 	for (brn = brevq; brn != NULL; brn = brn->brn_sibling) {
4930 		(void) strcpy(p, brn->brn_deviname);
4931 		(void) i_log_devfs_branch_remove(node_path);
4932 	}
4933 	*p = '\0';
4934 
4935 	free_brevq(brevq);
4936 }
4937 
4938 /*
4939  * log the events queued up on the branch event queue and free the
4940  * associated memory. Same as the previous function but operates on dip.
4941  */
4942 static void
4943 log_and_free_brevq_dip(dev_info_t *dip, struct brevq_node *brevq)
4944 {
4945 	char *path;
4946 
4947 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4948 	(void) ddi_pathname(dip, path);
4949 	log_and_free_brevq(path, brevq);
4950 	kmem_free(path, MAXPATHLEN);
4951 }
4952 
4953 /*
4954  * log the outstanding branch remove events for the grand children of the dip
4955  * and free the associated memory.
4956  */
4957 static void
4958 log_and_free_br_events_on_grand_children(dev_info_t *dip,
4959     struct brevq_node *brevq)
4960 {
4961 	struct brevq_node *brn;
4962 	char *path;
4963 	char *p;
4964 
4965 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4966 	(void) ddi_pathname(dip, path);
4967 	p = path + strlen(path);
4968 	for (brn = brevq; brn != NULL; brn = brn->brn_sibling) {
4969 		if (brn->brn_child) {
4970 			(void) strcpy(p, brn->brn_deviname);
4971 			/* now path contains the node path to the dip's child */
4972 			log_and_free_brevq(path, brn->brn_child);
4973 			brn->brn_child = NULL;
4974 		}
4975 	}
4976 	kmem_free(path, MAXPATHLEN);
4977 }
4978 
4979 /*
4980  * log and cleanup branch remove events for the grand children of the dip.
4981  */
4982 static void
4983 cleanup_br_events_on_grand_children(dev_info_t *dip, struct brevq_node **brevqp)
4984 {
4985 	dev_info_t *child;
4986 	struct brevq_node *brevq, *brn, *prev_brn, *next_brn;
4987 	char *path;
4988 	int circ;
4989 
4990 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4991 	prev_brn = NULL;
4992 	brevq = *brevqp;
4993 
4994 	ndi_devi_enter(dip, &circ);
4995 	for (brn = brevq; brn != NULL; brn = next_brn) {
4996 		next_brn = brn->brn_sibling;
4997 		for (child = ddi_get_child(dip); child != NULL;
4998 		    child = ddi_get_next_sibling(child)) {
4999 			if (i_ddi_node_state(child) >= DS_INITIALIZED) {
5000 				(void) ddi_deviname(child, path);
5001 				if (strcmp(path, brn->brn_deviname) == 0)
5002 					break;
5003 			}
5004 		}
5005 
5006 		if (child != NULL && !(DEVI_EVREMOVE(child))) {
5007 			/*
5008 			 * Event state is not REMOVE. So branch remove event
5009 			 * is not going be generated on brn->brn_child.
5010 			 * If any branch remove events were queued up on
5011 			 * brn->brn_child log them and remove the brn
5012 			 * from the queue.
5013 			 */
5014 			if (brn->brn_child) {
5015 				(void) ddi_pathname(dip, path);
5016 				(void) strcat(path, brn->brn_deviname);
5017 				log_and_free_brevq(path, brn->brn_child);
5018 			}
5019 
5020 			if (prev_brn)
5021 				prev_brn->brn_sibling = next_brn;
5022 			else
5023 				*brevqp = next_brn;
5024 
5025 			kmem_free(brn->brn_deviname,
5026 			    strlen(brn->brn_deviname) + 1);
5027 			kmem_free(brn, sizeof (*brn));
5028 		} else {
5029 			/*
5030 			 * Free up the outstanding branch remove events
5031 			 * queued on brn->brn_child since brn->brn_child
5032 			 * itself is eligible for branch remove event.
5033 			 */
5034 			if (brn->brn_child) {
5035 				free_brevq(brn->brn_child);
5036 				brn->brn_child = NULL;
5037 			}
5038 			prev_brn = brn;
5039 		}
5040 	}
5041 
5042 	ndi_devi_exit(dip, circ);
5043 	kmem_free(path, MAXPATHLEN);
5044 }
5045 
5046 static int
5047 need_remove_event(dev_info_t *dip, int flags)
5048 {
5049 	if ((flags & (NDI_NO_EVENT | NDI_AUTODETACH)) == 0 &&
5050 	    (flags & (NDI_DEVI_OFFLINE | NDI_UNCONFIG | NDI_DEVI_REMOVE)) &&
5051 	    !(DEVI_EVREMOVE(dip)))
5052 		return (1);
5053 	else
5054 		return (0);
5055 }
5056 
5057 /*
5058  * Unconfigure children/descendants of the dip.
5059  *
5060  * If the operation involves a branch event NDI_BRANCH_EVENT_OP is set
5061  * through out the unconfiguration. On successful return *brevqp is set to
5062  * a queue of dip's child devinames for which branch remove events need
5063  * to be generated.
5064  */
5065 static int
5066 devi_unconfig_branch(dev_info_t *dip, dev_info_t **dipp, int flags,
5067     struct brevq_node **brevqp)
5068 {
5069 	int rval;
5070 
5071 	*brevqp = NULL;
5072 
5073 	if ((!(flags & NDI_BRANCH_EVENT_OP)) && need_remove_event(dip, flags))
5074 		flags |= NDI_BRANCH_EVENT_OP;
5075 
5076 	if (flags & NDI_BRANCH_EVENT_OP) {
5077 		rval = devi_unconfig_common(dip, dipp, flags, DDI_MAJOR_T_NONE,
5078 		    brevqp);
5079 
5080 		if (rval != NDI_SUCCESS && (*brevqp)) {
5081 			log_and_free_brevq_dip(dip, *brevqp);
5082 			*brevqp = NULL;
5083 		}
5084 	} else
5085 		rval = devi_unconfig_common(dip, dipp, flags, DDI_MAJOR_T_NONE,
5086 		    NULL);
5087 
5088 	return (rval);
5089 }
5090 
5091 /*
5092  * If the dip is already bound to a driver transition to DS_INITIALIZED
5093  * in order to generate an event in the case where the node was left in
5094  * DS_BOUND state since boot (never got attached) and the node is now
5095  * being offlined.
5096  */
5097 static void
5098 init_bound_node_ev(dev_info_t *pdip, dev_info_t *dip, int flags)
5099 {
5100 	if (need_remove_event(dip, flags) &&
5101 	    i_ddi_node_state(dip) == DS_BOUND &&
5102 	    i_ddi_devi_attached(pdip) && !DEVI_IS_DEVICE_OFFLINE(dip))
5103 		(void) ddi_initchild(pdip, dip);
5104 }
5105 
5106 /*
5107  * attach a node/branch with parent already held busy
5108  */
5109 static int
5110 devi_attach_node(dev_info_t *dip, uint_t flags)
5111 {
5112 	dev_info_t *pdip = ddi_get_parent(dip);
5113 
5114 	ASSERT(pdip && DEVI_BUSY_OWNED(pdip));
5115 
5116 	mutex_enter(&(DEVI(dip)->devi_lock));
5117 	if (flags & NDI_DEVI_ONLINE) {
5118 		if (!i_ddi_devi_attached(dip))
5119 			DEVI_SET_REPORT(dip);
5120 		DEVI_SET_DEVICE_ONLINE(dip);
5121 	}
5122 	if (DEVI_IS_DEVICE_OFFLINE(dip)) {
5123 		mutex_exit(&(DEVI(dip)->devi_lock));
5124 		return (NDI_FAILURE);
5125 	}
5126 	mutex_exit(&(DEVI(dip)->devi_lock));
5127 
5128 	if (i_ddi_attachchild(dip) != DDI_SUCCESS) {
5129 		mutex_enter(&(DEVI(dip)->devi_lock));
5130 		DEVI_SET_EVUNINIT(dip);
5131 		mutex_exit(&(DEVI(dip)->devi_lock));
5132 
5133 		if (ndi_dev_is_persistent_node(dip))
5134 			(void) ddi_uninitchild(dip);
5135 		else {
5136 			/*
5137 			 * Delete .conf nodes and nodes that are not
5138 			 * well formed.
5139 			 */
5140 			(void) ddi_remove_child(dip, 0);
5141 		}
5142 		return (NDI_FAILURE);
5143 	}
5144 
5145 	i_ndi_devi_report_status_change(dip, NULL);
5146 
5147 	/*
5148 	 * log an event, but not during devfs lookups in which case
5149 	 * NDI_NO_EVENT is set.
5150 	 */
5151 	if ((flags & NDI_NO_EVENT) == 0 && !(DEVI_EVADD(dip))) {
5152 		(void) i_log_devfs_add_devinfo(dip, flags);
5153 
5154 		mutex_enter(&(DEVI(dip)->devi_lock));
5155 		DEVI_SET_EVADD(dip);
5156 		mutex_exit(&(DEVI(dip)->devi_lock));
5157 	} else if (!(flags & NDI_NO_EVENT_STATE_CHNG)) {
5158 		mutex_enter(&(DEVI(dip)->devi_lock));
5159 		DEVI_SET_EVADD(dip);
5160 		mutex_exit(&(DEVI(dip)->devi_lock));
5161 	}
5162 
5163 	return (NDI_SUCCESS);
5164 }
5165 
5166 /* internal function to config immediate children */
5167 static int
5168 config_immediate_children(dev_info_t *pdip, uint_t flags, major_t major)
5169 {
5170 	dev_info_t	*child, *next;
5171 	int		circ;
5172 
5173 	ASSERT(i_ddi_devi_attached(pdip));
5174 
5175 	if (!NEXUS_DRV(ddi_get_driver(pdip)))
5176 		return (NDI_SUCCESS);
5177 
5178 	NDI_CONFIG_DEBUG((CE_CONT,
5179 	    "config_immediate_children: %s%d (%p), flags=%x\n",
5180 	    ddi_driver_name(pdip), ddi_get_instance(pdip),
5181 	    (void *)pdip, flags));
5182 
5183 	ndi_devi_enter(pdip, &circ);
5184 
5185 	if (flags & NDI_CONFIG_REPROBE) {
5186 		mutex_enter(&DEVI(pdip)->devi_lock);
5187 		DEVI(pdip)->devi_flags &= ~DEVI_MADE_CHILDREN;
5188 		mutex_exit(&DEVI(pdip)->devi_lock);
5189 	}
5190 	(void) i_ndi_make_spec_children(pdip, flags);
5191 	i_ndi_init_hw_children(pdip, flags);
5192 
5193 	child = ddi_get_child(pdip);
5194 	while (child) {
5195 		/* NOTE: devi_attach_node() may remove the dip */
5196 		next = ddi_get_next_sibling(child);
5197 
5198 		/*
5199 		 * Configure all nexus nodes or leaf nodes with
5200 		 * matching driver major
5201 		 */
5202 		if ((major == DDI_MAJOR_T_NONE) ||
5203 		    (major == ddi_driver_major(child)) ||
5204 		    ((flags & NDI_CONFIG) && (is_leaf_node(child) == 0)))
5205 			(void) devi_attach_node(child, flags);
5206 		child = next;
5207 	}
5208 
5209 	ndi_devi_exit(pdip, circ);
5210 
5211 	return (NDI_SUCCESS);
5212 }
5213 
5214 /* internal function to config grand children */
5215 static int
5216 config_grand_children(dev_info_t *pdip, uint_t flags, major_t major)
5217 {
5218 	struct mt_config_handle *hdl;
5219 
5220 	/* multi-threaded configuration of child nexus */
5221 	hdl = mt_config_init(pdip, NULL, flags, major, MT_CONFIG_OP, NULL);
5222 	mt_config_children(hdl);
5223 
5224 	return (mt_config_fini(hdl));	/* wait for threads to exit */
5225 }
5226 
5227 /*
5228  * Common function for device tree configuration,
5229  * either BUS_CONFIG_ALL or BUS_CONFIG_DRIVER.
5230  * The NDI_CONFIG flag causes recursive configuration of
5231  * grandchildren, devfs usage should not recurse.
5232  */
5233 static int
5234 devi_config_common(dev_info_t *dip, int flags, major_t major)
5235 {
5236 	int error;
5237 	int (*f)();
5238 
5239 	if (!i_ddi_devi_attached(dip))
5240 		return (NDI_FAILURE);
5241 
5242 	if (pm_pre_config(dip, NULL) != DDI_SUCCESS)
5243 		return (NDI_FAILURE);
5244 
5245 	if ((DEVI(dip)->devi_ops->devo_bus_ops == NULL) ||
5246 	    (DEVI(dip)->devi_ops->devo_bus_ops->busops_rev < BUSO_REV_5) ||
5247 	    (f = DEVI(dip)->devi_ops->devo_bus_ops->bus_config) == NULL) {
5248 		error = config_immediate_children(dip, flags, major);
5249 	} else {
5250 		/* call bus_config entry point */
5251 		ddi_bus_config_op_t bus_op = (major == DDI_MAJOR_T_NONE) ?
5252 		    BUS_CONFIG_ALL : BUS_CONFIG_DRIVER;
5253 		error = (*f)(dip,
5254 		    flags, bus_op, (void *)(uintptr_t)major, NULL, 0);
5255 	}
5256 
5257 	if (error) {
5258 		pm_post_config(dip, NULL);
5259 		return (error);
5260 	}
5261 
5262 	/*
5263 	 * Some callers, notably SCSI, need to mark the devfs cache
5264 	 * to be rebuilt together with the config operation.
5265 	 */
5266 	if (flags & NDI_DEVFS_CLEAN)
5267 		(void) devfs_clean(dip, NULL, 0);
5268 
5269 	if (flags & NDI_CONFIG)
5270 		(void) config_grand_children(dip, flags, major);
5271 
5272 	pm_post_config(dip, NULL);
5273 
5274 	return (NDI_SUCCESS);
5275 }
5276 
5277 /*
5278  * Framework entry point for BUS_CONFIG_ALL
5279  */
5280 int
5281 ndi_devi_config(dev_info_t *dip, int flags)
5282 {
5283 	NDI_CONFIG_DEBUG((CE_CONT,
5284 	    "ndi_devi_config: par = %s%d (%p), flags = 0x%x\n",
5285 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
5286 
5287 	return (devi_config_common(dip, flags, DDI_MAJOR_T_NONE));
5288 }
5289 
5290 /*
5291  * Framework entry point for BUS_CONFIG_DRIVER, bound to major
5292  */
5293 int
5294 ndi_devi_config_driver(dev_info_t *dip, int flags, major_t major)
5295 {
5296 	/* don't abuse this function */
5297 	ASSERT(major != DDI_MAJOR_T_NONE);
5298 
5299 	NDI_CONFIG_DEBUG((CE_CONT,
5300 	    "ndi_devi_config_driver: par = %s%d (%p), flags = 0x%x\n",
5301 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
5302 
5303 	return (devi_config_common(dip, flags, major));
5304 }
5305 
5306 /*
5307  * Called by nexus drivers to configure its children.
5308  */
5309 static int
5310 devi_config_one(dev_info_t *pdip, char *devnm, dev_info_t **cdipp,
5311     uint_t flags, clock_t timeout)
5312 {
5313 	dev_info_t	*vdip = NULL;
5314 	char		*drivername = NULL;
5315 	int		find_by_addr = 0;
5316 	char		*name, *addr;
5317 	int		v_circ, p_circ;
5318 	clock_t		end_time;	/* 60 sec */
5319 	int		probed;
5320 	dev_info_t	*cdip;
5321 	mdi_pathinfo_t	*cpip;
5322 
5323 	*cdipp = NULL;
5324 
5325 	if (!NEXUS_DRV(ddi_get_driver(pdip)))
5326 		return (NDI_FAILURE);
5327 
5328 	/* split name into "name@addr" parts */
5329 	i_ddi_parse_name(devnm, &name, &addr, NULL);
5330 
5331 	/*
5332 	 * If the nexus is a pHCI and we are not processing a pHCI from
5333 	 * mdi bus_config code then we need to know the vHCI.
5334 	 */
5335 	if (MDI_PHCI(pdip))
5336 		vdip = mdi_devi_get_vdip(pdip);
5337 
5338 	/*
5339 	 * We may have a genericname on a system that creates drivername
5340 	 * nodes (from .conf files).  Find the drivername by nodeid. If we
5341 	 * can't find a node with devnm as the node name then we search by
5342 	 * drivername.  This allows an implementation to supply a genericly
5343 	 * named boot path (disk) and locate drivename nodes (sd).  The
5344 	 * NDI_PROMNAME flag does not apply to /devices/pseudo paths.
5345 	 */
5346 	if ((flags & NDI_PROMNAME) && (pdip != pseudo_dip)) {
5347 		drivername = child_path_to_driver(pdip, name, addr);
5348 		find_by_addr = 1;
5349 	}
5350 
5351 	/*
5352 	 * Determine end_time: This routine should *not* be called with a
5353 	 * constant non-zero timeout argument, the caller should be adjusting
5354 	 * the timeout argument relative to when it *started* its asynchronous
5355 	 * enumeration.
5356 	 */
5357 	if (timeout > 0)
5358 		end_time = ddi_get_lbolt() + timeout;
5359 
5360 	for (;;) {
5361 		/*
5362 		 * For pHCI, enter (vHCI, pHCI) and search for pathinfo/client
5363 		 * child - break out of for(;;) loop if child found.
5364 		 * NOTE: Lock order for ndi_devi_enter is (vHCI, pHCI).
5365 		 */
5366 		if (vdip) {
5367 			/* use mdi_devi_enter ordering */
5368 			ndi_devi_enter(vdip, &v_circ);
5369 			ndi_devi_enter(pdip, &p_circ);
5370 			cpip = mdi_pi_find(pdip, NULL, addr);
5371 			cdip = mdi_pi_get_client(cpip);
5372 			if (cdip)
5373 				break;
5374 		} else
5375 			ndi_devi_enter(pdip, &p_circ);
5376 
5377 		/*
5378 		 * When not a  vHCI or not all pHCI devices are required to
5379 		 * enumerated under the vHCI (NDI_MDI_FALLBACK) search for
5380 		 * devinfo child.
5381 		 */
5382 		if ((vdip == NULL) || (flags & NDI_MDI_FALLBACK)) {
5383 			/* determine if .conf nodes already built */
5384 			probed = (DEVI(pdip)->devi_flags & DEVI_MADE_CHILDREN);
5385 
5386 			/*
5387 			 * Search for child by name, if not found then search
5388 			 * for a node bound to the drivername driver with the
5389 			 * specified "@addr". Break out of for(;;) loop if
5390 			 * child found.  To support path-oriented aliases
5391 			 * binding on boot-device, we do a search_by_addr too.
5392 			 */
5393 again:			(void) i_ndi_make_spec_children(pdip, flags);
5394 			cdip = find_child_by_name(pdip, name, addr);
5395 			if ((cdip == NULL) && drivername)
5396 				cdip = find_child_by_driver(pdip,
5397 				    drivername, addr);
5398 			if ((cdip == NULL) && find_by_addr)
5399 				cdip = find_child_by_addr(pdip, addr);
5400 			if (cdip)
5401 				break;
5402 
5403 			/*
5404 			 * determine if we should reenumerate .conf nodes
5405 			 * and look for child again.
5406 			 */
5407 			if (probed &&
5408 			    i_ddi_io_initialized() &&
5409 			    (flags & NDI_CONFIG_REPROBE) &&
5410 			    ((timeout <= 0) || (ddi_get_lbolt() >= end_time))) {
5411 				probed = 0;
5412 				mutex_enter(&DEVI(pdip)->devi_lock);
5413 				DEVI(pdip)->devi_flags &= ~DEVI_MADE_CHILDREN;
5414 				mutex_exit(&DEVI(pdip)->devi_lock);
5415 				goto again;
5416 			}
5417 		}
5418 
5419 		/* break out of for(;;) if time expired */
5420 		if ((timeout <= 0) || (ddi_get_lbolt() >= end_time))
5421 			break;
5422 
5423 		/*
5424 		 * Child not found, exit and wait for asynchronous enumeration
5425 		 * to add child (or timeout). The addition of a new child (vhci
5426 		 * or phci) requires the asynchronous enumeration thread to
5427 		 * ndi_devi_enter/ndi_devi_exit. This exit will signal devi_cv
5428 		 * and cause us to return from ndi_devi_exit_and_wait, after
5429 		 * which we loop and search for the requested child again.
5430 		 */
5431 		NDI_DEBUG(flags, (CE_CONT,
5432 		    "%s%d: waiting for child %s@%s, timeout %ld",
5433 		    ddi_driver_name(pdip), ddi_get_instance(pdip),
5434 		    name, addr, timeout));
5435 		if (vdip) {
5436 			/*
5437 			 * Mark vHCI for pHCI ndi_devi_exit broadcast.
5438 			 */
5439 			mutex_enter(&DEVI(vdip)->devi_lock);
5440 			DEVI(vdip)->devi_flags |=
5441 			    DEVI_PHCI_SIGNALS_VHCI;
5442 			mutex_exit(&DEVI(vdip)->devi_lock);
5443 			ndi_devi_exit(pdip, p_circ);
5444 
5445 			/*
5446 			 * NB: There is a small race window from above
5447 			 * ndi_devi_exit() of pdip to cv_wait() in
5448 			 * ndi_devi_exit_and_wait() which can result in
5449 			 * not immediately finding a new pHCI child
5450 			 * of a pHCI that uses NDI_MDI_FAILBACK.
5451 			 */
5452 			ndi_devi_exit_and_wait(vdip, v_circ, end_time);
5453 		} else {
5454 			ndi_devi_exit_and_wait(pdip, p_circ, end_time);
5455 		}
5456 	}
5457 
5458 	/* done with paddr, fixup i_ddi_parse_name '@'->'\0' change */
5459 	if (addr && *addr != '\0')
5460 		*(addr - 1) = '@';
5461 
5462 	/* attach and hold the child, returning pointer to child */
5463 	if (cdip && (devi_attach_node(cdip, flags) == NDI_SUCCESS)) {
5464 		ndi_hold_devi(cdip);
5465 		*cdipp = cdip;
5466 	}
5467 
5468 	ndi_devi_exit(pdip, p_circ);
5469 	if (vdip)
5470 		ndi_devi_exit(vdip, v_circ);
5471 	return (*cdipp ? NDI_SUCCESS : NDI_FAILURE);
5472 }
5473 
5474 /*
5475  * Enumerate and attach a child specified by name 'devnm'.
5476  * Called by devfs lookup and DR to perform a BUS_CONFIG_ONE.
5477  * Note: devfs does not make use of NDI_CONFIG to configure
5478  * an entire branch.
5479  */
5480 int
5481 ndi_devi_config_one(dev_info_t *dip, char *devnm, dev_info_t **dipp, int flags)
5482 {
5483 	int error;
5484 	int (*f)();
5485 	int branch_event = 0;
5486 
5487 	ASSERT(dipp);
5488 	ASSERT(i_ddi_devi_attached(dip));
5489 
5490 	NDI_CONFIG_DEBUG((CE_CONT,
5491 	    "ndi_devi_config_one: par = %s%d (%p), child = %s\n",
5492 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, devnm));
5493 
5494 	if (pm_pre_config(dip, devnm) != DDI_SUCCESS)
5495 		return (NDI_FAILURE);
5496 
5497 	if ((flags & (NDI_NO_EVENT | NDI_BRANCH_EVENT_OP)) == 0 &&
5498 	    (flags & NDI_CONFIG)) {
5499 		flags |= NDI_BRANCH_EVENT_OP;
5500 		branch_event = 1;
5501 	}
5502 
5503 	if ((DEVI(dip)->devi_ops->devo_bus_ops == NULL) ||
5504 	    (DEVI(dip)->devi_ops->devo_bus_ops->busops_rev < BUSO_REV_5) ||
5505 	    (f = DEVI(dip)->devi_ops->devo_bus_ops->bus_config) == NULL) {
5506 		error = devi_config_one(dip, devnm, dipp, flags, 0);
5507 	} else {
5508 		/* call bus_config entry point */
5509 		error = (*f)(dip, flags, BUS_CONFIG_ONE, (void *)devnm, dipp);
5510 	}
5511 
5512 	if (error || (flags & NDI_CONFIG) == 0) {
5513 		pm_post_config(dip, devnm);
5514 		return (error);
5515 	}
5516 
5517 	/*
5518 	 * DR usage (i.e. call with NDI_CONFIG) recursively configures
5519 	 * grandchildren, performing a BUS_CONFIG_ALL from the node attached
5520 	 * by the BUS_CONFIG_ONE.
5521 	 */
5522 	ASSERT(*dipp);
5523 	error = devi_config_common(*dipp, flags, DDI_MAJOR_T_NONE);
5524 
5525 	pm_post_config(dip, devnm);
5526 
5527 	if (branch_event)
5528 		(void) i_log_devfs_branch_add(*dipp);
5529 
5530 	return (error);
5531 }
5532 
5533 
5534 /*
5535  * Enumerate and attach a child specified by name 'devnm'.
5536  * Called during configure the OBP options. This configures
5537  * only one node.
5538  */
5539 static int
5540 ndi_devi_config_obp_args(dev_info_t *parent, char *devnm,
5541     dev_info_t **childp, int flags)
5542 {
5543 	int error;
5544 	int (*f)();
5545 
5546 	ASSERT(childp);
5547 	ASSERT(i_ddi_devi_attached(parent));
5548 
5549 	NDI_CONFIG_DEBUG((CE_CONT, "ndi_devi_config_obp_args: "
5550 	    "par = %s%d (%p), child = %s\n", ddi_driver_name(parent),
5551 	    ddi_get_instance(parent), (void *)parent, devnm));
5552 
5553 	if ((DEVI(parent)->devi_ops->devo_bus_ops == NULL) ||
5554 	    (DEVI(parent)->devi_ops->devo_bus_ops->busops_rev < BUSO_REV_5) ||
5555 	    (f = DEVI(parent)->devi_ops->devo_bus_ops->bus_config) == NULL) {
5556 		error = NDI_FAILURE;
5557 	} else {
5558 		/* call bus_config entry point */
5559 		error = (*f)(parent, flags,
5560 		    BUS_CONFIG_OBP_ARGS, (void *)devnm, childp);
5561 	}
5562 	return (error);
5563 }
5564 
5565 /*
5566  * Pay attention, the following is a bit tricky:
5567  * There are three possible cases when constraints are applied
5568  *
5569  *	- A constraint is applied and the offline is disallowed.
5570  *	  Simply return failure and block the offline
5571  *
5572  *	- A constraint is applied and the offline is allowed.
5573  *	  Mark the dip as having passed the constraint and allow
5574  *	  offline to proceed.
5575  *
5576  *	- A constraint is not applied. Allow the offline to proceed for now.
5577  *
5578  * In the latter two cases we allow the offline to proceed. If the
5579  * offline succeeds (no users) everything is fine. It is ok for an unused
5580  * device to be offlined even if no constraints were imposed on the offline.
5581  * If the offline fails because there are users, we look at the constraint
5582  * flag on the dip. If the constraint flag is set (implying that it passed
5583  * a constraint) we allow the dip to be retired. If not, we don't allow
5584  * the retire. This ensures that we don't allow unconstrained retire.
5585  */
5586 int
5587 e_ddi_offline_notify(dev_info_t *dip)
5588 {
5589 	int retval;
5590 	int constraint;
5591 	int failure;
5592 
5593 	RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): entered: dip=%p",
5594 	    (void *) dip));
5595 
5596 	constraint = 0;
5597 	failure = 0;
5598 
5599 	/*
5600 	 * Start with userland constraints first - applied via device contracts
5601 	 */
5602 	retval = contract_device_offline(dip, DDI_DEV_T_ANY, 0);
5603 	switch (retval) {
5604 	case CT_NACK:
5605 		RIO_DEBUG((CE_NOTE, "Received NACK for dip=%p", (void *)dip));
5606 		failure = 1;
5607 		goto out;
5608 	case CT_ACK:
5609 		constraint = 1;
5610 		RIO_DEBUG((CE_NOTE, "Received ACK for dip=%p", (void *)dip));
5611 		break;
5612 	case CT_NONE:
5613 		/* no contracts */
5614 		RIO_DEBUG((CE_NOTE, "No contracts on dip=%p", (void *)dip));
5615 		break;
5616 	default:
5617 		ASSERT(retval == CT_NONE);
5618 	}
5619 
5620 	/*
5621 	 * Next, use LDI to impose kernel constraints
5622 	 */
5623 	retval = ldi_invoke_notify(dip, DDI_DEV_T_ANY, 0, LDI_EV_OFFLINE, NULL);
5624 	switch (retval) {
5625 	case LDI_EV_FAILURE:
5626 		contract_device_negend(dip, DDI_DEV_T_ANY, 0, CT_EV_FAILURE);
5627 		RIO_DEBUG((CE_NOTE, "LDI callback failed on dip=%p",
5628 		    (void *)dip));
5629 		failure = 1;
5630 		goto out;
5631 	case LDI_EV_SUCCESS:
5632 		constraint = 1;
5633 		RIO_DEBUG((CE_NOTE, "LDI callback success on dip=%p",
5634 		    (void *)dip));
5635 		break;
5636 	case LDI_EV_NONE:
5637 		/* no matching LDI callbacks */
5638 		RIO_DEBUG((CE_NOTE, "No LDI callbacks for dip=%p",
5639 		    (void *)dip));
5640 		break;
5641 	default:
5642 		ASSERT(retval == LDI_EV_NONE);
5643 	}
5644 
5645 out:
5646 	mutex_enter(&(DEVI(dip)->devi_lock));
5647 	if ((DEVI(dip)->devi_flags & DEVI_RETIRING) && failure) {
5648 		RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): setting "
5649 		    "BLOCKED flag. dip=%p", (void *)dip));
5650 		DEVI(dip)->devi_flags |= DEVI_R_BLOCKED;
5651 		if (DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT) {
5652 			RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): "
5653 			    "blocked. clearing RCM CONSTRAINT flag. dip=%p",
5654 			    (void *)dip));
5655 			DEVI(dip)->devi_flags &= ~DEVI_R_CONSTRAINT;
5656 		}
5657 	} else if ((DEVI(dip)->devi_flags & DEVI_RETIRING) && constraint) {
5658 		RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): setting "
5659 		    "CONSTRAINT flag. dip=%p", (void *)dip));
5660 		DEVI(dip)->devi_flags |= DEVI_R_CONSTRAINT;
5661 	} else if ((DEVI(dip)->devi_flags & DEVI_RETIRING) &&
5662 	    DEVI(dip)->devi_ref == 0) {
5663 		/* also allow retire if device is not in use */
5664 		RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): device not in "
5665 		    "use. Setting CONSTRAINT flag. dip=%p", (void *)dip));
5666 		DEVI(dip)->devi_flags |= DEVI_R_CONSTRAINT;
5667 	} else {
5668 		/*
5669 		 * Note: We cannot ASSERT here that DEVI_R_CONSTRAINT is
5670 		 * not set, since other sources (such as RCM) may have
5671 		 * set the flag.
5672 		 */
5673 		RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): not setting "
5674 		    "constraint flag. dip=%p", (void *)dip));
5675 	}
5676 	mutex_exit(&(DEVI(dip)->devi_lock));
5677 
5678 
5679 	RIO_VERBOSE((CE_NOTE, "e_ddi_offline_notify(): exit: dip=%p",
5680 	    (void *) dip));
5681 
5682 	return (failure ? DDI_FAILURE : DDI_SUCCESS);
5683 }
5684 
5685 void
5686 e_ddi_offline_finalize(dev_info_t *dip, int result)
5687 {
5688 	RIO_DEBUG((CE_NOTE, "e_ddi_offline_finalize(): entry: result=%s, "
5689 	    "dip=%p", result == DDI_SUCCESS ? "SUCCESS" : "FAILURE",
5690 	    (void *)dip));
5691 
5692 	contract_device_negend(dip, DDI_DEV_T_ANY, 0,  result == DDI_SUCCESS ?
5693 	    CT_EV_SUCCESS : CT_EV_FAILURE);
5694 
5695 	ldi_invoke_finalize(dip, DDI_DEV_T_ANY, 0,
5696 	    LDI_EV_OFFLINE, result == DDI_SUCCESS ?
5697 	    LDI_EV_SUCCESS : LDI_EV_FAILURE, NULL);
5698 
5699 	RIO_VERBOSE((CE_NOTE, "e_ddi_offline_finalize(): exit: dip=%p",
5700 	    (void *)dip));
5701 }
5702 
5703 void
5704 e_ddi_degrade_finalize(dev_info_t *dip)
5705 {
5706 	RIO_DEBUG((CE_NOTE, "e_ddi_degrade_finalize(): entry: "
5707 	    "result always = DDI_SUCCESS, dip=%p", (void *)dip));
5708 
5709 	contract_device_degrade(dip, DDI_DEV_T_ANY, 0);
5710 	contract_device_negend(dip, DDI_DEV_T_ANY, 0, CT_EV_SUCCESS);
5711 
5712 	ldi_invoke_finalize(dip, DDI_DEV_T_ANY, 0, LDI_EV_DEGRADE,
5713 	    LDI_EV_SUCCESS, NULL);
5714 
5715 	RIO_VERBOSE((CE_NOTE, "e_ddi_degrade_finalize(): exit: dip=%p",
5716 	    (void *)dip));
5717 }
5718 
5719 void
5720 e_ddi_undegrade_finalize(dev_info_t *dip)
5721 {
5722 	RIO_DEBUG((CE_NOTE, "e_ddi_undegrade_finalize(): entry: "
5723 	    "result always = DDI_SUCCESS, dip=%p", (void *)dip));
5724 
5725 	contract_device_undegrade(dip, DDI_DEV_T_ANY, 0);
5726 	contract_device_negend(dip, DDI_DEV_T_ANY, 0, CT_EV_SUCCESS);
5727 
5728 	RIO_VERBOSE((CE_NOTE, "e_ddi_undegrade_finalize(): exit: dip=%p",
5729 	    (void *)dip));
5730 }
5731 
5732 /*
5733  * detach a node with parent already held busy
5734  */
5735 static int
5736 devi_detach_node(dev_info_t *dip, uint_t flags)
5737 {
5738 	dev_info_t *pdip = ddi_get_parent(dip);
5739 	int ret = NDI_SUCCESS;
5740 	ddi_eventcookie_t cookie;
5741 	char *path = NULL;
5742 	char *class = NULL;
5743 	char *driver = NULL;
5744 	int instance = -1;
5745 	int post_event = 0;
5746 
5747 	ASSERT(pdip && DEVI_BUSY_OWNED(pdip));
5748 
5749 	/*
5750 	 * Invoke notify if offlining
5751 	 */
5752 	if (flags & NDI_DEVI_OFFLINE) {
5753 		RIO_DEBUG((CE_NOTE, "devi_detach_node: offlining dip=%p",
5754 		    (void *)dip));
5755 		if (e_ddi_offline_notify(dip) != DDI_SUCCESS) {
5756 			RIO_DEBUG((CE_NOTE, "devi_detach_node: offline NACKed"
5757 			    "dip=%p", (void *)dip));
5758 			return (NDI_FAILURE);
5759 		}
5760 	}
5761 
5762 	if (flags & NDI_POST_EVENT) {
5763 		if (i_ddi_devi_attached(pdip)) {
5764 			if (ddi_get_eventcookie(dip, DDI_DEVI_REMOVE_EVENT,
5765 			    &cookie) == NDI_SUCCESS)
5766 				(void) ndi_post_event(dip, dip, cookie, NULL);
5767 		}
5768 	}
5769 
5770 	if (i_ddi_detachchild(dip, flags) != DDI_SUCCESS) {
5771 		if (flags & NDI_DEVI_OFFLINE) {
5772 			RIO_DEBUG((CE_NOTE, "devi_detach_node: offline failed."
5773 			    " Calling e_ddi_offline_finalize with result=%d. "
5774 			    "dip=%p", DDI_FAILURE, (void *)dip));
5775 			e_ddi_offline_finalize(dip, DDI_FAILURE);
5776 		}
5777 		return (NDI_FAILURE);
5778 	}
5779 
5780 	if (flags & NDI_DEVI_OFFLINE) {
5781 		RIO_DEBUG((CE_NOTE, "devi_detach_node: offline succeeded."
5782 		    " Calling e_ddi_offline_finalize with result=%d, "
5783 		    "dip=%p", DDI_SUCCESS, (void *)dip));
5784 		e_ddi_offline_finalize(dip, DDI_SUCCESS);
5785 	}
5786 
5787 	if (flags & NDI_AUTODETACH)
5788 		return (NDI_SUCCESS);
5789 
5790 	/*
5791 	 * For DR, even bound nodes may need to have offline
5792 	 * flag set.
5793 	 */
5794 	if (flags & NDI_DEVI_OFFLINE) {
5795 		mutex_enter(&(DEVI(dip)->devi_lock));
5796 		DEVI_SET_DEVICE_OFFLINE(dip);
5797 		mutex_exit(&(DEVI(dip)->devi_lock));
5798 	}
5799 
5800 	if (i_ddi_node_state(dip) == DS_INITIALIZED) {
5801 		path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
5802 		(void) ddi_pathname(dip, path);
5803 		if (flags & NDI_DEVI_OFFLINE)
5804 			i_ndi_devi_report_status_change(dip, path);
5805 
5806 		if (need_remove_event(dip, flags)) {
5807 			post_event = 1;
5808 			class = i_ddi_strdup(i_ddi_devi_class(dip), KM_SLEEP);
5809 			driver = i_ddi_strdup((char *)ddi_driver_name(dip),
5810 			    KM_SLEEP);
5811 			instance = ddi_get_instance(dip);
5812 
5813 			mutex_enter(&(DEVI(dip)->devi_lock));
5814 			DEVI_SET_EVREMOVE(dip);
5815 			mutex_exit(&(DEVI(dip)->devi_lock));
5816 		}
5817 	}
5818 
5819 	if (flags & (NDI_UNCONFIG | NDI_DEVI_REMOVE)) {
5820 		ret = ddi_uninitchild(dip);
5821 		if (ret == NDI_SUCCESS) {
5822 			/*
5823 			 * Remove uninitialized pseudo nodes because
5824 			 * system props are lost and the node cannot be
5825 			 * reattached.
5826 			 */
5827 			if (!ndi_dev_is_persistent_node(dip))
5828 				flags |= NDI_DEVI_REMOVE;
5829 
5830 			if (flags & NDI_DEVI_REMOVE) {
5831 				ret = ddi_remove_child(dip, 0);
5832 				if (post_event && ret == NDI_SUCCESS) {
5833 					(void) i_log_devfs_remove_devinfo(path,
5834 					    class, driver, instance, flags);
5835 				}
5836 			}
5837 
5838 		}
5839 	}
5840 
5841 	if (path)
5842 		kmem_free(path, MAXPATHLEN);
5843 	if (class)
5844 		kmem_free(class, strlen(class) + 1);
5845 	if (driver)
5846 		kmem_free(driver, strlen(driver) + 1);
5847 
5848 	return (ret);
5849 }
5850 
5851 /*
5852  * unconfigure immediate children of bus nexus device
5853  */
5854 static int
5855 unconfig_immediate_children(
5856 	dev_info_t *dip,
5857 	dev_info_t **dipp,
5858 	int flags,
5859 	major_t major)
5860 {
5861 	int rv = NDI_SUCCESS;
5862 	int circ, vcirc;
5863 	dev_info_t *child;
5864 	dev_info_t *vdip = NULL;
5865 	dev_info_t *next;
5866 
5867 	ASSERT(dipp == NULL || *dipp == NULL);
5868 
5869 	/*
5870 	 * Scan forward to see if we will be processing a pHCI child. If we
5871 	 * have a child that is a pHCI and vHCI and pHCI are not siblings then
5872 	 * enter vHCI before parent(pHCI) to prevent deadlock with mpxio
5873 	 * Client power management operations.
5874 	 */
5875 	ndi_devi_enter(dip, &circ);
5876 	for (child = ddi_get_child(dip); child;
5877 	    child = ddi_get_next_sibling(child)) {
5878 		/* skip same nodes we skip below */
5879 		if (((major != DDI_MAJOR_T_NONE) &&
5880 		    (major != ddi_driver_major(child))) ||
5881 		    ((flags & NDI_AUTODETACH) && !is_leaf_node(child)))
5882 			continue;
5883 
5884 		if (MDI_PHCI(child)) {
5885 			vdip = mdi_devi_get_vdip(child);
5886 			/*
5887 			 * If vHCI and vHCI is not a sibling of pHCI
5888 			 * then enter in (vHCI, parent(pHCI)) order.
5889 			 */
5890 			if (vdip && (ddi_get_parent(vdip) != dip)) {
5891 				ndi_devi_exit(dip, circ);
5892 
5893 				/* use mdi_devi_enter ordering */
5894 				ndi_devi_enter(vdip, &vcirc);
5895 				ndi_devi_enter(dip, &circ);
5896 				break;
5897 			} else
5898 				vdip = NULL;
5899 		}
5900 	}
5901 
5902 	child = ddi_get_child(dip);
5903 	while (child) {
5904 		next = ddi_get_next_sibling(child);
5905 
5906 		if ((major != DDI_MAJOR_T_NONE) &&
5907 		    (major != ddi_driver_major(child))) {
5908 			child = next;
5909 			continue;
5910 		}
5911 
5912 		/* skip nexus nodes during autodetach */
5913 		if ((flags & NDI_AUTODETACH) && !is_leaf_node(child)) {
5914 			child = next;
5915 			continue;
5916 		}
5917 
5918 		if (devi_detach_node(child, flags) != NDI_SUCCESS) {
5919 			if (dipp && *dipp == NULL) {
5920 				ndi_hold_devi(child);
5921 				*dipp = child;
5922 			}
5923 			rv = NDI_FAILURE;
5924 		}
5925 
5926 		/*
5927 		 * Continue upon failure--best effort algorithm
5928 		 */
5929 		child = next;
5930 	}
5931 
5932 	ndi_devi_exit(dip, circ);
5933 	if (vdip)
5934 		ndi_devi_exit(vdip, vcirc);
5935 
5936 	return (rv);
5937 }
5938 
5939 /*
5940  * unconfigure grand children of bus nexus device
5941  */
5942 static int
5943 unconfig_grand_children(
5944 	dev_info_t *dip,
5945 	dev_info_t **dipp,
5946 	int flags,
5947 	major_t major,
5948 	struct brevq_node **brevqp)
5949 {
5950 	struct mt_config_handle *hdl;
5951 
5952 	if (brevqp)
5953 		*brevqp = NULL;
5954 
5955 	/* multi-threaded configuration of child nexus */
5956 	hdl = mt_config_init(dip, dipp, flags, major, MT_UNCONFIG_OP, brevqp);
5957 	mt_config_children(hdl);
5958 
5959 	return (mt_config_fini(hdl));	/* wait for threads to exit */
5960 }
5961 
5962 /*
5963  * Unconfigure children/descendants of the dip.
5964  *
5965  * If brevqp is not NULL, on return *brevqp is set to a queue of dip's
5966  * child devinames for which branch remove events need to be generated.
5967  */
5968 static int
5969 devi_unconfig_common(
5970 	dev_info_t *dip,
5971 	dev_info_t **dipp,
5972 	int flags,
5973 	major_t major,
5974 	struct brevq_node **brevqp)
5975 {
5976 	int rv;
5977 	int pm_cookie;
5978 	int (*f)();
5979 	ddi_bus_config_op_t bus_op;
5980 
5981 	if (dipp)
5982 		*dipp = NULL;
5983 	if (brevqp)
5984 		*brevqp = NULL;
5985 
5986 	/*
5987 	 * Power up the dip if it is powered off.  If the flag bit
5988 	 * NDI_AUTODETACH is set and the dip is not at its full power,
5989 	 * skip the rest of the branch.
5990 	 */
5991 	if (pm_pre_unconfig(dip, flags, &pm_cookie, NULL) != DDI_SUCCESS)
5992 		return ((flags & NDI_AUTODETACH) ? NDI_SUCCESS :
5993 		    NDI_FAILURE);
5994 
5995 	/*
5996 	 * Some callers, notably SCSI, need to clear out the devfs
5997 	 * cache together with the unconfig to prevent stale entries.
5998 	 */
5999 	if (flags & NDI_DEVFS_CLEAN)
6000 		(void) devfs_clean(dip, NULL, 0);
6001 
6002 	rv = unconfig_grand_children(dip, dipp, flags, major, brevqp);
6003 
6004 	if ((rv != NDI_SUCCESS) && ((flags & NDI_AUTODETACH) == 0)) {
6005 		if (brevqp && *brevqp) {
6006 			log_and_free_br_events_on_grand_children(dip, *brevqp);
6007 			free_brevq(*brevqp);
6008 			*brevqp = NULL;
6009 		}
6010 		pm_post_unconfig(dip, pm_cookie, NULL);
6011 		return (rv);
6012 	}
6013 
6014 	if (dipp && *dipp) {
6015 		ndi_rele_devi(*dipp);
6016 		*dipp = NULL;
6017 	}
6018 
6019 	/*
6020 	 * It is possible to have a detached nexus with children
6021 	 * and grandchildren (for example: a branch consisting
6022 	 * entirely of bound nodes.) Since the nexus is detached
6023 	 * the bus_unconfig entry point cannot be used to remove
6024 	 * or unconfigure the descendants.
6025 	 */
6026 	if (!i_ddi_devi_attached(dip) ||
6027 	    (DEVI(dip)->devi_ops->devo_bus_ops == NULL) ||
6028 	    (DEVI(dip)->devi_ops->devo_bus_ops->busops_rev < BUSO_REV_5) ||
6029 	    (f = DEVI(dip)->devi_ops->devo_bus_ops->bus_unconfig) == NULL) {
6030 		rv = unconfig_immediate_children(dip, dipp, flags, major);
6031 	} else {
6032 		/*
6033 		 * call bus_unconfig entry point
6034 		 * It should reset nexus flags if unconfigure succeeds.
6035 		 */
6036 		bus_op = (major == DDI_MAJOR_T_NONE) ?
6037 		    BUS_UNCONFIG_ALL : BUS_UNCONFIG_DRIVER;
6038 		rv = (*f)(dip, flags, bus_op, (void *)(uintptr_t)major);
6039 	}
6040 
6041 	pm_post_unconfig(dip, pm_cookie, NULL);
6042 
6043 	if (brevqp && *brevqp)
6044 		cleanup_br_events_on_grand_children(dip, brevqp);
6045 
6046 	return (rv);
6047 }
6048 
6049 /*
6050  * called by devfs/framework to unconfigure children bound to major
6051  * If NDI_AUTODETACH is specified, this is invoked by either the
6052  * moduninstall daemon or the modunload -i 0 command.
6053  */
6054 int
6055 ndi_devi_unconfig_driver(dev_info_t *dip, int flags, major_t major)
6056 {
6057 	NDI_CONFIG_DEBUG((CE_CONT,
6058 	    "ndi_devi_unconfig_driver: par = %s%d (%p), flags = 0x%x\n",
6059 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
6060 
6061 	return (devi_unconfig_common(dip, NULL, flags, major, NULL));
6062 }
6063 
6064 int
6065 ndi_devi_unconfig(dev_info_t *dip, int flags)
6066 {
6067 	NDI_CONFIG_DEBUG((CE_CONT,
6068 	    "ndi_devi_unconfig: par = %s%d (%p), flags = 0x%x\n",
6069 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
6070 
6071 	return (devi_unconfig_common(dip, NULL, flags, DDI_MAJOR_T_NONE, NULL));
6072 }
6073 
6074 int
6075 e_ddi_devi_unconfig(dev_info_t *dip, dev_info_t **dipp, int flags)
6076 {
6077 	NDI_CONFIG_DEBUG((CE_CONT,
6078 	    "e_ddi_devi_unconfig: par = %s%d (%p), flags = 0x%x\n",
6079 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip, flags));
6080 
6081 	return (devi_unconfig_common(dip, dipp, flags, DDI_MAJOR_T_NONE, NULL));
6082 }
6083 
6084 /*
6085  * Unconfigure child by name
6086  */
6087 static int
6088 devi_unconfig_one(dev_info_t *pdip, char *devnm, int flags)
6089 {
6090 	int		rv, circ;
6091 	dev_info_t	*child;
6092 	dev_info_t	*vdip = NULL;
6093 	int		v_circ;
6094 
6095 	ndi_devi_enter(pdip, &circ);
6096 	child = ndi_devi_findchild(pdip, devnm);
6097 
6098 	/*
6099 	 * If child is pHCI and vHCI and pHCI are not siblings then enter vHCI
6100 	 * before parent(pHCI) to avoid deadlock with mpxio Client power
6101 	 * management operations.
6102 	 */
6103 	if (child && MDI_PHCI(child)) {
6104 		vdip = mdi_devi_get_vdip(child);
6105 		if (vdip && (ddi_get_parent(vdip) != pdip)) {
6106 			ndi_devi_exit(pdip, circ);
6107 
6108 			/* use mdi_devi_enter ordering */
6109 			ndi_devi_enter(vdip, &v_circ);
6110 			ndi_devi_enter(pdip, &circ);
6111 			child = ndi_devi_findchild(pdip, devnm);
6112 		} else
6113 			vdip = NULL;
6114 	}
6115 
6116 	if (child) {
6117 		rv = devi_detach_node(child, flags);
6118 	} else {
6119 		NDI_CONFIG_DEBUG((CE_CONT,
6120 		    "devi_unconfig_one: %s not found\n", devnm));
6121 		rv = NDI_SUCCESS;
6122 	}
6123 
6124 	ndi_devi_exit(pdip, circ);
6125 	if (vdip)
6126 		ndi_devi_exit(vdip, v_circ);
6127 
6128 	return (rv);
6129 }
6130 
6131 int
6132 ndi_devi_unconfig_one(
6133 	dev_info_t *pdip,
6134 	char *devnm,
6135 	dev_info_t **dipp,
6136 	int flags)
6137 {
6138 	int		(*f)();
6139 	int		circ, rv;
6140 	int		pm_cookie;
6141 	dev_info_t	*child;
6142 	dev_info_t	*vdip = NULL;
6143 	int		v_circ;
6144 	struct brevq_node *brevq = NULL;
6145 
6146 	ASSERT(i_ddi_devi_attached(pdip));
6147 
6148 	NDI_CONFIG_DEBUG((CE_CONT,
6149 	    "ndi_devi_unconfig_one: par = %s%d (%p), child = %s\n",
6150 	    ddi_driver_name(pdip), ddi_get_instance(pdip),
6151 	    (void *)pdip, devnm));
6152 
6153 	if (pm_pre_unconfig(pdip, flags, &pm_cookie, devnm) != DDI_SUCCESS)
6154 		return (NDI_FAILURE);
6155 
6156 	if (dipp)
6157 		*dipp = NULL;
6158 
6159 	ndi_devi_enter(pdip, &circ);
6160 	child = ndi_devi_findchild(pdip, devnm);
6161 
6162 	/*
6163 	 * If child is pHCI and vHCI and pHCI are not siblings then enter vHCI
6164 	 * before parent(pHCI) to avoid deadlock with mpxio Client power
6165 	 * management operations.
6166 	 */
6167 	if (child && MDI_PHCI(child)) {
6168 		vdip = mdi_devi_get_vdip(child);
6169 		if (vdip && (ddi_get_parent(vdip) != pdip)) {
6170 			ndi_devi_exit(pdip, circ);
6171 
6172 			/* use mdi_devi_enter ordering */
6173 			ndi_devi_enter(vdip, &v_circ);
6174 			ndi_devi_enter(pdip, &circ);
6175 			child = ndi_devi_findchild(pdip, devnm);
6176 		} else
6177 			vdip = NULL;
6178 	}
6179 
6180 	if (child == NULL) {
6181 		NDI_CONFIG_DEBUG((CE_CONT, "ndi_devi_unconfig_one: %s"
6182 		    " not found\n", devnm));
6183 		rv = NDI_SUCCESS;
6184 		goto out;
6185 	}
6186 
6187 	/*
6188 	 * Unconfigure children/descendants of named child
6189 	 */
6190 	rv = devi_unconfig_branch(child, dipp, flags | NDI_UNCONFIG, &brevq);
6191 	if (rv != NDI_SUCCESS)
6192 		goto out;
6193 
6194 	init_bound_node_ev(pdip, child, flags);
6195 
6196 	if ((DEVI(pdip)->devi_ops->devo_bus_ops == NULL) ||
6197 	    (DEVI(pdip)->devi_ops->devo_bus_ops->busops_rev < BUSO_REV_5) ||
6198 	    (f = DEVI(pdip)->devi_ops->devo_bus_ops->bus_unconfig) == NULL) {
6199 		rv = devi_detach_node(child, flags);
6200 	} else {
6201 		/* call bus_config entry point */
6202 		rv = (*f)(pdip, flags, BUS_UNCONFIG_ONE, (void *)devnm);
6203 	}
6204 
6205 	if (brevq) {
6206 		if (rv != NDI_SUCCESS)
6207 			log_and_free_brevq_dip(child, brevq);
6208 		else
6209 			free_brevq(brevq);
6210 	}
6211 
6212 	if (dipp && rv != NDI_SUCCESS) {
6213 		ndi_hold_devi(child);
6214 		ASSERT(*dipp == NULL);
6215 		*dipp = child;
6216 	}
6217 
6218 out:
6219 	ndi_devi_exit(pdip, circ);
6220 	if (vdip)
6221 		ndi_devi_exit(vdip, v_circ);
6222 
6223 	pm_post_unconfig(pdip, pm_cookie, devnm);
6224 
6225 	return (rv);
6226 }
6227 
6228 struct async_arg {
6229 	dev_info_t *dip;
6230 	uint_t flags;
6231 };
6232 
6233 /*
6234  * Common async handler for:
6235  *	ndi_devi_bind_driver_async
6236  *	ndi_devi_online_async
6237  */
6238 static int
6239 i_ndi_devi_async_common(dev_info_t *dip, uint_t flags, void (*func)())
6240 {
6241 	int tqflag;
6242 	int kmflag;
6243 	struct async_arg *arg;
6244 	dev_info_t *pdip = ddi_get_parent(dip);
6245 
6246 	ASSERT(pdip);
6247 	ASSERT(DEVI(pdip)->devi_taskq);
6248 	ASSERT(ndi_dev_is_persistent_node(dip));
6249 
6250 	if (flags & NDI_NOSLEEP) {
6251 		kmflag = KM_NOSLEEP;
6252 		tqflag = TQ_NOSLEEP;
6253 	} else {
6254 		kmflag = KM_SLEEP;
6255 		tqflag = TQ_SLEEP;
6256 	}
6257 
6258 	arg = kmem_alloc(sizeof (*arg), kmflag);
6259 	if (arg == NULL)
6260 		goto fail;
6261 
6262 	arg->flags = flags;
6263 	arg->dip = dip;
6264 	if (ddi_taskq_dispatch(DEVI(pdip)->devi_taskq, func, arg, tqflag) ==
6265 	    DDI_SUCCESS) {
6266 		return (NDI_SUCCESS);
6267 	}
6268 
6269 fail:
6270 	NDI_CONFIG_DEBUG((CE_CONT, "%s%d: ddi_taskq_dispatch failed",
6271 	    ddi_driver_name(pdip), ddi_get_instance(pdip)));
6272 
6273 	if (arg)
6274 		kmem_free(arg, sizeof (*arg));
6275 	return (NDI_FAILURE);
6276 }
6277 
6278 static void
6279 i_ndi_devi_bind_driver_cb(struct async_arg *arg)
6280 {
6281 	(void) ndi_devi_bind_driver(arg->dip, arg->flags);
6282 	kmem_free(arg, sizeof (*arg));
6283 }
6284 
6285 int
6286 ndi_devi_bind_driver_async(dev_info_t *dip, uint_t flags)
6287 {
6288 	return (i_ndi_devi_async_common(dip, flags,
6289 	    (void (*)())i_ndi_devi_bind_driver_cb));
6290 }
6291 
6292 /*
6293  * place the devinfo in the ONLINE state.
6294  */
6295 int
6296 ndi_devi_online(dev_info_t *dip, uint_t flags)
6297 {
6298 	int circ, rv;
6299 	dev_info_t *pdip = ddi_get_parent(dip);
6300 	int branch_event = 0;
6301 
6302 	ASSERT(pdip);
6303 
6304 	NDI_CONFIG_DEBUG((CE_CONT, "ndi_devi_online: %s%d (%p)\n",
6305 	    ddi_driver_name(dip), ddi_get_instance(dip), (void *)dip));
6306 
6307 	ndi_devi_enter(pdip, &circ);
6308 	/* bind child before merging .conf nodes */
6309 	rv = i_ndi_config_node(dip, DS_BOUND, flags);
6310 	if (rv != NDI_SUCCESS) {
6311 		ndi_devi_exit(pdip, circ);
6312 		return (rv);
6313 	}
6314 
6315 	/* merge .conf properties */
6316 	(void) i_ndi_make_spec_children(pdip, flags);
6317 
6318 	flags |= (NDI_DEVI_ONLINE | NDI_CONFIG);
6319 
6320 	if (flags & NDI_NO_EVENT) {
6321 		/*
6322 		 * Caller is specifically asking for not to generate an event.
6323 		 * Set the following flag so that devi_attach_node() don't
6324 		 * change the event state.
6325 		 */
6326 		flags |= NDI_NO_EVENT_STATE_CHNG;
6327 	}
6328 
6329 	if ((flags & (NDI_NO_EVENT | NDI_BRANCH_EVENT_OP)) == 0 &&
6330 	    ((flags & NDI_CONFIG) || DEVI_NEED_NDI_CONFIG(dip))) {
6331 		flags |= NDI_BRANCH_EVENT_OP;
6332 		branch_event = 1;
6333 	}
6334 
6335 	/*
6336 	 * devi_attach_node() may remove dip on failure
6337 	 */
6338 	if ((rv = devi_attach_node(dip, flags)) == NDI_SUCCESS) {
6339 		if ((flags & NDI_CONFIG) || DEVI_NEED_NDI_CONFIG(dip)) {
6340 			(void) ndi_devi_config(dip, flags);
6341 		}
6342 
6343 		if (branch_event)
6344 			(void) i_log_devfs_branch_add(dip);
6345 	}
6346 
6347 	ndi_devi_exit(pdip, circ);
6348 
6349 	/*
6350 	 * Notify devfs that we have a new node. Devfs needs to invalidate
6351 	 * cached directory contents.
6352 	 *
6353 	 * For PCMCIA devices, it is possible the pdip is not fully
6354 	 * attached. In this case, calling back into devfs will
6355 	 * result in a loop or assertion error. Hence, the check
6356 	 * on node state.
6357 	 *
6358 	 * If we own parent lock, this is part of a branch operation.
6359 	 * We skip the devfs_clean() step because the cache invalidation
6360 	 * is done higher up in the device tree.
6361 	 */
6362 	if (rv == NDI_SUCCESS && i_ddi_devi_attached(pdip) &&
6363 	    !DEVI_BUSY_OWNED(pdip))
6364 		(void) devfs_clean(pdip, NULL, 0);
6365 	return (rv);
6366 }
6367 
6368 static void
6369 i_ndi_devi_online_cb(struct async_arg *arg)
6370 {
6371 	(void) ndi_devi_online(arg->dip, arg->flags);
6372 	kmem_free(arg, sizeof (*arg));
6373 }
6374 
6375 int
6376 ndi_devi_online_async(dev_info_t *dip, uint_t flags)
6377 {
6378 	/* mark child as need config if requested. */
6379 	if (flags & NDI_CONFIG) {
6380 		mutex_enter(&(DEVI(dip)->devi_lock));
6381 		DEVI_SET_NDI_CONFIG(dip);
6382 		mutex_exit(&(DEVI(dip)->devi_lock));
6383 	}
6384 
6385 	return (i_ndi_devi_async_common(dip, flags,
6386 	    (void (*)())i_ndi_devi_online_cb));
6387 }
6388 
6389 /*
6390  * Take a device node Offline
6391  * To take a device Offline means to detach the device instance from
6392  * the driver and prevent devfs requests from re-attaching the device
6393  * instance.
6394  *
6395  * The flag NDI_DEVI_REMOVE causes removes the device node from
6396  * the driver list and the device tree. In this case, the device
6397  * is assumed to be removed from the system.
6398  */
6399 int
6400 ndi_devi_offline(dev_info_t *dip, uint_t flags)
6401 {
6402 	int		circ, rval = 0;
6403 	dev_info_t	*pdip = ddi_get_parent(dip);
6404 	dev_info_t	*vdip = NULL;
6405 	int		v_circ;
6406 	struct brevq_node *brevq = NULL;
6407 
6408 	ASSERT(pdip);
6409 
6410 	flags |= NDI_DEVI_OFFLINE;
6411 
6412 	/*
6413 	 * If child is pHCI and vHCI and pHCI are not siblings then enter vHCI
6414 	 * before parent(pHCI) to avoid deadlock with mpxio Client power
6415 	 * management operations.
6416 	 */
6417 	if (MDI_PHCI(dip)) {
6418 		vdip = mdi_devi_get_vdip(dip);
6419 		if (vdip && (ddi_get_parent(vdip) != pdip))
6420 			ndi_devi_enter(vdip, &v_circ);
6421 		else
6422 			vdip = NULL;
6423 	}
6424 	ndi_devi_enter(pdip, &circ);
6425 
6426 	if (i_ddi_devi_attached(dip)) {
6427 		/*
6428 		 * If dip is in DS_READY state, there may be cached dv_nodes
6429 		 * referencing this dip, so we invoke devfs code path.
6430 		 * Note that we must release busy changing on pdip to
6431 		 * avoid deadlock against devfs.
6432 		 */
6433 		char *devname = kmem_alloc(MAXNAMELEN + 1, KM_SLEEP);
6434 		(void) ddi_deviname(dip, devname);
6435 
6436 		ndi_devi_exit(pdip, circ);
6437 		if (vdip)
6438 			ndi_devi_exit(vdip, v_circ);
6439 
6440 		/*
6441 		 * If we are explictly told to clean, then clean. If we own the
6442 		 * parent lock then this is part of a branch operation, and we
6443 		 * skip the devfs_clean() step.
6444 		 *
6445 		 * NOTE: A thread performing a devfs file system lookup/
6446 		 * bus_config can't call devfs_clean to unconfig without
6447 		 * causing rwlock problems in devfs. For ndi_devi_offline, this
6448 		 * means that the NDI_DEVFS_CLEAN flag is safe from ioctl code
6449 		 * or from an async hotplug thread, but is not safe from a
6450 		 * nexus driver's bus_config implementation.
6451 		 */
6452 		if ((flags & NDI_DEVFS_CLEAN) ||
6453 		    (!DEVI_BUSY_OWNED(pdip)))
6454 			(void) devfs_clean(pdip, devname + 1, DV_CLEAN_FORCE);
6455 
6456 		kmem_free(devname, MAXNAMELEN + 1);
6457 
6458 		rval = devi_unconfig_branch(dip, NULL, flags|NDI_UNCONFIG,
6459 		    &brevq);
6460 
6461 		if (rval)
6462 			return (NDI_FAILURE);
6463 
6464 		if (vdip)
6465 			ndi_devi_enter(vdip, &v_circ);
6466 		ndi_devi_enter(pdip, &circ);
6467 	}
6468 
6469 	init_bound_node_ev(pdip, dip, flags);
6470 
6471 	rval = devi_detach_node(dip, flags);
6472 	if (brevq) {
6473 		if (rval != NDI_SUCCESS)
6474 			log_and_free_brevq_dip(dip, brevq);
6475 		else
6476 			free_brevq(brevq);
6477 	}
6478 
6479 	ndi_devi_exit(pdip, circ);
6480 	if (vdip)
6481 		ndi_devi_exit(vdip, v_circ);
6482 
6483 	return (rval);
6484 }
6485 
6486 /*
6487  * Find the child dev_info node of parent nexus 'p' whose unit address
6488  * matches "cname@caddr".  Recommend use of ndi_devi_findchild() instead.
6489  */
6490 dev_info_t *
6491 ndi_devi_find(dev_info_t *pdip, char *cname, char *caddr)
6492 {
6493 	dev_info_t *child;
6494 	int circ;
6495 
6496 	if (pdip == NULL || cname == NULL || caddr == NULL)
6497 		return ((dev_info_t *)NULL);
6498 
6499 	ndi_devi_enter(pdip, &circ);
6500 	child = find_sibling(ddi_get_child(pdip), cname, caddr,
6501 	    FIND_NODE_BY_NODENAME, NULL);
6502 	ndi_devi_exit(pdip, circ);
6503 	return (child);
6504 }
6505 
6506 /*
6507  * Find the child dev_info node of parent nexus 'p' whose unit address
6508  * matches devname "name@addr".  Permits caller to hold the parent.
6509  */
6510 dev_info_t *
6511 ndi_devi_findchild(dev_info_t *pdip, char *devname)
6512 {
6513 	dev_info_t *child;
6514 	char	*cname, *caddr;
6515 	char	*devstr;
6516 
6517 	ASSERT(DEVI_BUSY_OWNED(pdip));
6518 
6519 	devstr = i_ddi_strdup(devname, KM_SLEEP);
6520 	i_ddi_parse_name(devstr, &cname, &caddr, NULL);
6521 
6522 	if (cname == NULL || caddr == NULL) {
6523 		kmem_free(devstr, strlen(devname)+1);
6524 		return ((dev_info_t *)NULL);
6525 	}
6526 
6527 	child = find_sibling(ddi_get_child(pdip), cname, caddr,
6528 	    FIND_NODE_BY_NODENAME, NULL);
6529 	kmem_free(devstr, strlen(devname)+1);
6530 	return (child);
6531 }
6532 
6533 /*
6534  * Misc. routines called by framework only
6535  */
6536 
6537 /*
6538  * Clear the DEVI_MADE_CHILDREN/DEVI_ATTACHED_CHILDREN flags
6539  * if new child spec has been added.
6540  */
6541 static int
6542 reset_nexus_flags(dev_info_t *dip, void *arg)
6543 {
6544 	struct hwc_spec	*list;
6545 	int		circ;
6546 
6547 	if (((DEVI(dip)->devi_flags & DEVI_MADE_CHILDREN) == 0) ||
6548 	    ((list = hwc_get_child_spec(dip, (major_t)(uintptr_t)arg)) == NULL))
6549 		return (DDI_WALK_CONTINUE);
6550 
6551 	hwc_free_spec_list(list);
6552 
6553 	/* coordinate child state update */
6554 	ndi_devi_enter(dip, &circ);
6555 	mutex_enter(&DEVI(dip)->devi_lock);
6556 	DEVI(dip)->devi_flags &= ~(DEVI_MADE_CHILDREN | DEVI_ATTACHED_CHILDREN);
6557 	mutex_exit(&DEVI(dip)->devi_lock);
6558 	ndi_devi_exit(dip, circ);
6559 
6560 	return (DDI_WALK_CONTINUE);
6561 }
6562 
6563 /*
6564  * Helper functions, returns NULL if no memory.
6565  */
6566 
6567 /*
6568  * path_to_major:
6569  *
6570  * Return an alternate driver name binding for the leaf device
6571  * of the given pathname, if there is one. The purpose of this
6572  * function is to deal with generic pathnames. The default action
6573  * for platforms that can't do this (ie: x86 or any platform that
6574  * does not have prom_finddevice functionality, which matches
6575  * nodenames and unit-addresses without the drivers participation)
6576  * is to return DDI_MAJOR_T_NONE.
6577  *
6578  * Used in loadrootmodules() in the swapgeneric module to
6579  * associate a given pathname with a given leaf driver.
6580  *
6581  */
6582 major_t
6583 path_to_major(char *path)
6584 {
6585 	dev_info_t *dip;
6586 	char *p, *q;
6587 	pnode_t nodeid;
6588 	major_t major;
6589 
6590 	/* check for path-oriented alias */
6591 	major = ddi_name_to_major(path);
6592 	if ((major != DDI_MAJOR_T_NONE) &&
6593 	    !(devnamesp[major].dn_flags & DN_DRIVER_REMOVED)) {
6594 		NDI_CONFIG_DEBUG((CE_NOTE, "path_to_major: %s path bound %s\n",
6595 		    path, ddi_major_to_name(major)));
6596 		return (major);
6597 	}
6598 
6599 	/*
6600 	 * Get the nodeid of the given pathname, if such a mapping exists.
6601 	 */
6602 	dip = NULL;
6603 	nodeid = prom_finddevice(path);
6604 	if (nodeid != OBP_BADNODE) {
6605 		/*
6606 		 * Find the nodeid in our copy of the device tree and return
6607 		 * whatever name we used to bind this node to a driver.
6608 		 */
6609 		dip = e_ddi_nodeid_to_dip(nodeid);
6610 	}
6611 
6612 	if (dip == NULL) {
6613 		NDI_CONFIG_DEBUG((CE_WARN,
6614 		    "path_to_major: can't bind <%s>\n", path));
6615 		return (DDI_MAJOR_T_NONE);
6616 	}
6617 
6618 	/*
6619 	 * If we're bound to something other than the nodename,
6620 	 * note that in the message buffer and system log.
6621 	 */
6622 	p = ddi_binding_name(dip);
6623 	q = ddi_node_name(dip);
6624 	if (p && q && (strcmp(p, q) != 0))
6625 		NDI_CONFIG_DEBUG((CE_NOTE, "path_to_major: %s bound to %s\n",
6626 		    path, p));
6627 
6628 	major = ddi_name_to_major(p);
6629 
6630 	ndi_rele_devi(dip);		/* release e_ddi_nodeid_to_dip hold */
6631 
6632 	return (major);
6633 }
6634 
6635 /*
6636  * Return the held dip for the specified major and instance, attempting to do
6637  * an attach if specified. Return NULL if the devi can't be found or put in
6638  * the proper state. The caller must release the hold via ddi_release_devi if
6639  * a non-NULL value is returned.
6640  *
6641  * Some callers expect to be able to perform a hold_devi() while in a context
6642  * where using ndi_devi_enter() to ensure the hold might cause deadlock (see
6643  * open-from-attach code in consconfig_dacf.c). Such special-case callers
6644  * must ensure that an ndi_devi_enter(parent)/ndi_hold_devi() from a safe
6645  * context is already active. The hold_devi() implementation must accommodate
6646  * these callers.
6647  */
6648 static dev_info_t *
6649 hold_devi(major_t major, int instance, int flags)
6650 {
6651 	struct devnames	*dnp;
6652 	dev_info_t	*dip;
6653 	char		*path;
6654 	char		*vpath;
6655 
6656 	if ((major >= devcnt) || (instance == -1))
6657 		return (NULL);
6658 
6659 	/* try to find the instance in the per driver list */
6660 	dnp = &(devnamesp[major]);
6661 	LOCK_DEV_OPS(&(dnp->dn_lock));
6662 	for (dip = dnp->dn_head; dip;
6663 	    dip = (dev_info_t *)DEVI(dip)->devi_next) {
6664 		/* skip node if instance field is not valid */
6665 		if (i_ddi_node_state(dip) < DS_INITIALIZED)
6666 			continue;
6667 
6668 		/* look for instance match */
6669 		if (DEVI(dip)->devi_instance == instance) {
6670 			/*
6671 			 * To accommodate callers that can't block in
6672 			 * ndi_devi_enter() we do an ndi_hold_devi(), and
6673 			 * afterwards check that the node is in a state where
6674 			 * the hold prevents detach(). If we did not manage to
6675 			 * prevent detach then we ndi_rele_devi() and perform
6676 			 * the slow path below (which can result in a blocking
6677 			 * ndi_devi_enter() while driving attach top-down).
6678 			 * This code depends on the ordering of
6679 			 * DEVI_SET_DETACHING and the devi_ref check in the
6680 			 * detach_node() code path.
6681 			 */
6682 			ndi_hold_devi(dip);
6683 			if (i_ddi_devi_attached(dip) &&
6684 			    !DEVI_IS_DETACHING(dip)) {
6685 				UNLOCK_DEV_OPS(&(dnp->dn_lock));
6686 				return (dip);	/* fast-path with devi held */
6687 			}
6688 			ndi_rele_devi(dip);
6689 
6690 			/* try slow-path */
6691 			dip = NULL;
6692 			break;
6693 		}
6694 	}
6695 	ASSERT(dip == NULL);
6696 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
6697 
6698 	if (flags & E_DDI_HOLD_DEVI_NOATTACH)
6699 		return (NULL);		/* told not to drive attach */
6700 
6701 	/* slow-path may block, so it should not occur from interrupt */
6702 	ASSERT(!servicing_interrupt());
6703 	if (servicing_interrupt())
6704 		return (NULL);
6705 
6706 	/* reconstruct the path and drive attach by path through devfs. */
6707 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6708 	if (e_ddi_majorinstance_to_path(major, instance, path) == 0) {
6709 		dip = e_ddi_hold_devi_by_path(path, flags);
6710 
6711 		/*
6712 		 * Verify that we got the correct device - a path_to_inst file
6713 		 * with a bogus/corrupt path (or a nexus that changes its
6714 		 * unit-address format) could result in an incorrect answer
6715 		 *
6716 		 * Verify major, instance, and path.
6717 		 */
6718 		vpath = kmem_alloc(MAXPATHLEN, KM_SLEEP);
6719 		if (dip &&
6720 		    ((DEVI(dip)->devi_major != major) ||
6721 		    ((DEVI(dip)->devi_instance != instance)) ||
6722 		    (strcmp(path, ddi_pathname(dip, vpath)) != 0))) {
6723 			ndi_rele_devi(dip);
6724 			dip = NULL;	/* no answer better than wrong answer */
6725 		}
6726 		kmem_free(vpath, MAXPATHLEN);
6727 	}
6728 	kmem_free(path, MAXPATHLEN);
6729 	return (dip);			/* with devi held */
6730 }
6731 
6732 /*
6733  * The {e_}ddi_hold_devi{_by_{instance|dev|path}} hold the devinfo node
6734  * associated with the specified arguments.  This hold should be released
6735  * by calling ddi_release_devi.
6736  *
6737  * The E_DDI_HOLD_DEVI_NOATTACH flag argument allows the caller to to specify
6738  * a failure return if the node is not already attached.
6739  *
6740  * NOTE: by the time we make e_ddi_hold_devi public, we should be able to reuse
6741  * ddi_hold_devi again.
6742  */
6743 dev_info_t *
6744 ddi_hold_devi_by_instance(major_t major, int instance, int flags)
6745 {
6746 	return (hold_devi(major, instance, flags));
6747 }
6748 
6749 dev_info_t *
6750 e_ddi_hold_devi_by_dev(dev_t dev, int flags)
6751 {
6752 	major_t	major = getmajor(dev);
6753 	dev_info_t	*dip;
6754 	struct dev_ops	*ops;
6755 	dev_info_t	*ddip = NULL;
6756 
6757 	dip = hold_devi(major, dev_to_instance(dev), flags);
6758 
6759 	/*
6760 	 * The rest of this routine is legacy support for drivers that
6761 	 * have broken DDI_INFO_DEVT2INSTANCE implementations but may have
6762 	 * functional DDI_INFO_DEVT2DEVINFO implementations.  This code will
6763 	 * diagnose inconsistency and, for maximum compatibility with legacy
6764 	 * drivers, give preference to the drivers DDI_INFO_DEVT2DEVINFO
6765 	 * implementation over the above derived dip based the driver's
6766 	 * DDI_INFO_DEVT2INSTANCE implementation. This legacy support should
6767 	 * be removed when DDI_INFO_DEVT2DEVINFO is deprecated.
6768 	 *
6769 	 * NOTE: The following code has a race condition. DEVT2DEVINFO
6770 	 *	returns a dip which is not held. By the time we ref ddip,
6771 	 *	it could have been freed. The saving grace is that for
6772 	 *	most drivers, the dip returned from hold_devi() is the
6773 	 *	same one as the one returned by DEVT2DEVINFO, so we are
6774 	 *	safe for drivers with the correct getinfo(9e) impl.
6775 	 */
6776 	if (((ops = ddi_hold_driver(major)) != NULL) &&
6777 	    CB_DRV_INSTALLED(ops) && ops->devo_getinfo)  {
6778 		if ((*ops->devo_getinfo)(NULL, DDI_INFO_DEVT2DEVINFO,
6779 		    (void *)dev, (void **)&ddip) != DDI_SUCCESS)
6780 			ddip = NULL;
6781 	}
6782 
6783 	/* give preference to the driver returned DEVT2DEVINFO dip */
6784 	if (ddip && (dip != ddip)) {
6785 #ifdef	DEBUG
6786 		cmn_err(CE_WARN, "%s: inconsistent getinfo(9E) implementation",
6787 		    ddi_driver_name(ddip));
6788 #endif	/* DEBUG */
6789 		ndi_hold_devi(ddip);
6790 		if (dip)
6791 			ndi_rele_devi(dip);
6792 		dip = ddip;
6793 	}
6794 
6795 	if (ops)
6796 		ddi_rele_driver(major);
6797 
6798 	return (dip);
6799 }
6800 
6801 /*
6802  * For compatibility only. Do not call this function!
6803  */
6804 dev_info_t *
6805 e_ddi_get_dev_info(dev_t dev, vtype_t type)
6806 {
6807 	dev_info_t *dip = NULL;
6808 	if (getmajor(dev) >= devcnt)
6809 		return (NULL);
6810 
6811 	switch (type) {
6812 	case VCHR:
6813 	case VBLK:
6814 		dip = e_ddi_hold_devi_by_dev(dev, 0);
6815 	default:
6816 		break;
6817 	}
6818 
6819 	/*
6820 	 * For compatibility reasons, we can only return the dip with
6821 	 * the driver ref count held. This is not a safe thing to do.
6822 	 * For certain broken third-party software, we are willing
6823 	 * to venture into unknown territory.
6824 	 */
6825 	if (dip) {
6826 		(void) ndi_hold_driver(dip);
6827 		ndi_rele_devi(dip);
6828 	}
6829 	return (dip);
6830 }
6831 
6832 dev_info_t *
6833 e_ddi_hold_devi_by_path(char *path, int flags)
6834 {
6835 	dev_info_t	*dip;
6836 
6837 	/* can't specify NOATTACH by path */
6838 	ASSERT(!(flags & E_DDI_HOLD_DEVI_NOATTACH));
6839 
6840 	return (resolve_pathname(path, &dip, NULL, NULL) ? NULL : dip);
6841 }
6842 
6843 void
6844 e_ddi_hold_devi(dev_info_t *dip)
6845 {
6846 	ndi_hold_devi(dip);
6847 }
6848 
6849 void
6850 ddi_release_devi(dev_info_t *dip)
6851 {
6852 	ndi_rele_devi(dip);
6853 }
6854 
6855 /*
6856  * Associate a streams queue with a devinfo node
6857  * NOTE: This function is called by STREAM driver's put procedure.
6858  *	It cannot block.
6859  */
6860 void
6861 ddi_assoc_queue_with_devi(queue_t *q, dev_info_t *dip)
6862 {
6863 	queue_t *rq = _RD(q);
6864 	struct stdata *stp;
6865 	vnode_t *vp;
6866 
6867 	/* set flag indicating that ddi_assoc_queue_with_devi was called */
6868 	mutex_enter(QLOCK(rq));
6869 	rq->q_flag |= _QASSOCIATED;
6870 	mutex_exit(QLOCK(rq));
6871 
6872 	/* get the vnode associated with the queue */
6873 	stp = STREAM(rq);
6874 	vp = stp->sd_vnode;
6875 	ASSERT(vp);
6876 
6877 	/* change the hardware association of the vnode */
6878 	spec_assoc_vp_with_devi(vp, dip);
6879 }
6880 
6881 /*
6882  * ddi_install_driver(name)
6883  *
6884  * Driver installation is currently a byproduct of driver loading.  This
6885  * may change.
6886  */
6887 int
6888 ddi_install_driver(char *name)
6889 {
6890 	major_t major = ddi_name_to_major(name);
6891 
6892 	if ((major == DDI_MAJOR_T_NONE) ||
6893 	    (ddi_hold_installed_driver(major) == NULL)) {
6894 		return (DDI_FAILURE);
6895 	}
6896 	ddi_rele_driver(major);
6897 	return (DDI_SUCCESS);
6898 }
6899 
6900 struct dev_ops *
6901 ddi_hold_driver(major_t major)
6902 {
6903 	return (mod_hold_dev_by_major(major));
6904 }
6905 
6906 
6907 void
6908 ddi_rele_driver(major_t major)
6909 {
6910 	mod_rele_dev_by_major(major);
6911 }
6912 
6913 
6914 /*
6915  * This is called during boot to force attachment order of special dips
6916  * dip must be referenced via ndi_hold_devi()
6917  */
6918 int
6919 i_ddi_attach_node_hierarchy(dev_info_t *dip)
6920 {
6921 	dev_info_t	*parent;
6922 	int		ret, circ;
6923 
6924 	/*
6925 	 * Recurse up until attached parent is found.
6926 	 */
6927 	if (i_ddi_devi_attached(dip))
6928 		return (DDI_SUCCESS);
6929 	parent = ddi_get_parent(dip);
6930 	if (i_ddi_attach_node_hierarchy(parent) != DDI_SUCCESS)
6931 		return (DDI_FAILURE);
6932 
6933 	/*
6934 	 * Come top-down, expanding .conf nodes under this parent
6935 	 * and driving attach.
6936 	 */
6937 	ndi_devi_enter(parent, &circ);
6938 	(void) i_ndi_make_spec_children(parent, 0);
6939 	ret = i_ddi_attachchild(dip);
6940 	ndi_devi_exit(parent, circ);
6941 
6942 	return (ret);
6943 }
6944 
6945 /* keep this function static */
6946 static int
6947 attach_driver_nodes(major_t major)
6948 {
6949 	struct devnames *dnp;
6950 	dev_info_t *dip;
6951 	int error = DDI_FAILURE;
6952 	int circ;
6953 
6954 	dnp = &devnamesp[major];
6955 	LOCK_DEV_OPS(&dnp->dn_lock);
6956 	dip = dnp->dn_head;
6957 	while (dip) {
6958 		ndi_hold_devi(dip);
6959 		UNLOCK_DEV_OPS(&dnp->dn_lock);
6960 		if (i_ddi_attach_node_hierarchy(dip) == DDI_SUCCESS)
6961 			error = DDI_SUCCESS;
6962 		/*
6963 		 * Set the 'ddi-config-driver-node' property on a nexus
6964 		 * node to cause attach_driver_nodes() to configure all
6965 		 * immediate children of the nexus. This property should
6966 		 * be set on nodes with immediate children that bind to
6967 		 * the same driver as parent.
6968 		 */
6969 		if ((error == DDI_SUCCESS) && (ddi_prop_exists(DDI_DEV_T_ANY,
6970 		    dip, DDI_PROP_DONTPASS, "ddi-config-driver-node"))) {
6971 			ndi_devi_enter(dip, &circ);
6972 			(void) ndi_devi_config(dip, NDI_NO_EVENT);
6973 			ndi_devi_exit(dip, circ);
6974 		}
6975 		LOCK_DEV_OPS(&dnp->dn_lock);
6976 		ndi_rele_devi(dip);
6977 		dip = ddi_get_next(dip);
6978 	}
6979 	if (error == DDI_SUCCESS)
6980 		dnp->dn_flags |= DN_NO_AUTODETACH;
6981 	UNLOCK_DEV_OPS(&dnp->dn_lock);
6982 
6983 
6984 	return (error);
6985 }
6986 
6987 /*
6988  * i_ddi_attach_hw_nodes configures and attaches all hw nodes
6989  * bound to a specific driver. This function replaces calls to
6990  * ddi_hold_installed_driver() for drivers with no .conf
6991  * enumerated nodes.
6992  *
6993  * This facility is typically called at boot time to attach
6994  * platform-specific hardware nodes, such as ppm nodes on xcal
6995  * and grover and keyswitch nodes on cherrystone. It does not
6996  * deal with .conf enumerated node. Calling it beyond the boot
6997  * process is strongly discouraged.
6998  */
6999 int
7000 i_ddi_attach_hw_nodes(char *driver)
7001 {
7002 	major_t major;
7003 
7004 	major = ddi_name_to_major(driver);
7005 	if (major == DDI_MAJOR_T_NONE)
7006 		return (DDI_FAILURE);
7007 
7008 	return (attach_driver_nodes(major));
7009 }
7010 
7011 /*
7012  * i_ddi_attach_pseudo_node configures pseudo drivers which
7013  * has a single node. The .conf nodes must be enumerated
7014  * before calling this interface. The dip is held attached
7015  * upon returning.
7016  *
7017  * This facility should only be called only at boot time
7018  * by the I/O framework.
7019  */
7020 dev_info_t *
7021 i_ddi_attach_pseudo_node(char *driver)
7022 {
7023 	major_t major;
7024 	dev_info_t *dip;
7025 
7026 	major = ddi_name_to_major(driver);
7027 	if (major == DDI_MAJOR_T_NONE)
7028 		return (NULL);
7029 
7030 	if (attach_driver_nodes(major) != DDI_SUCCESS)
7031 		return (NULL);
7032 
7033 	dip = devnamesp[major].dn_head;
7034 	ASSERT(dip && ddi_get_next(dip) == NULL);
7035 	ndi_hold_devi(dip);
7036 	return (dip);
7037 }
7038 
7039 static void
7040 diplist_to_parent_major(dev_info_t *head, char parents[])
7041 {
7042 	major_t major;
7043 	dev_info_t *dip, *pdip;
7044 
7045 	for (dip = head; dip != NULL; dip = ddi_get_next(dip)) {
7046 		pdip = ddi_get_parent(dip);
7047 		ASSERT(pdip);	/* disallow rootnex.conf nodes */
7048 		major = ddi_driver_major(pdip);
7049 		if ((major != DDI_MAJOR_T_NONE) && parents[major] == 0)
7050 			parents[major] = 1;
7051 	}
7052 }
7053 
7054 /*
7055  * Call ddi_hold_installed_driver() on each parent major
7056  * and invoke mt_config_driver() to attach child major.
7057  * This is part of the implementation of ddi_hold_installed_driver.
7058  */
7059 static int
7060 attach_driver_by_parent(major_t child_major, char parents[])
7061 {
7062 	major_t par_major;
7063 	struct mt_config_handle *hdl;
7064 	int flags = NDI_DEVI_PERSIST | NDI_NO_EVENT;
7065 
7066 	hdl = mt_config_init(NULL, NULL, flags, child_major, MT_CONFIG_OP,
7067 	    NULL);
7068 	for (par_major = 0; par_major < devcnt; par_major++) {
7069 		/* disallow recursion on the same driver */
7070 		if (parents[par_major] == 0 || par_major == child_major)
7071 			continue;
7072 		if (ddi_hold_installed_driver(par_major) == NULL)
7073 			continue;
7074 		hdl->mtc_parmajor = par_major;
7075 		mt_config_driver(hdl);
7076 		ddi_rele_driver(par_major);
7077 	}
7078 	(void) mt_config_fini(hdl);
7079 
7080 	return (i_ddi_devs_attached(child_major));
7081 }
7082 
7083 int
7084 i_ddi_devs_attached(major_t major)
7085 {
7086 	dev_info_t *dip;
7087 	struct devnames *dnp;
7088 	int error = DDI_FAILURE;
7089 
7090 	/* check for attached instances */
7091 	dnp = &devnamesp[major];
7092 	LOCK_DEV_OPS(&dnp->dn_lock);
7093 	for (dip = dnp->dn_head; dip != NULL; dip = ddi_get_next(dip)) {
7094 		if (i_ddi_devi_attached(dip)) {
7095 			error = DDI_SUCCESS;
7096 			break;
7097 		}
7098 	}
7099 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7100 
7101 	return (error);
7102 }
7103 
7104 int
7105 i_ddi_minor_node_count(dev_info_t *ddip, const char *node_type)
7106 {
7107 	int			circ;
7108 	struct ddi_minor_data	*dp;
7109 	int			count = 0;
7110 
7111 	ndi_devi_enter(ddip, &circ);
7112 	for (dp = DEVI(ddip)->devi_minor; dp != NULL; dp = dp->next) {
7113 		if (strcmp(dp->ddm_node_type, node_type) == 0)
7114 			count++;
7115 	}
7116 	ndi_devi_exit(ddip, circ);
7117 	return (count);
7118 }
7119 
7120 /*
7121  * ddi_hold_installed_driver configures and attaches all
7122  * instances of the specified driver. To accomplish this
7123  * it configures and attaches all possible parents of
7124  * the driver, enumerated both in h/w nodes and in the
7125  * driver's .conf file.
7126  *
7127  * NOTE: This facility is for compatibility purposes only and will
7128  *	eventually go away. Its usage is strongly discouraged.
7129  */
7130 static void
7131 enter_driver(struct devnames *dnp)
7132 {
7133 	mutex_enter(&dnp->dn_lock);
7134 	ASSERT(dnp->dn_busy_thread != curthread);
7135 	while (dnp->dn_flags & DN_DRIVER_BUSY)
7136 		cv_wait(&dnp->dn_wait, &dnp->dn_lock);
7137 	dnp->dn_flags |= DN_DRIVER_BUSY;
7138 	dnp->dn_busy_thread = curthread;
7139 	mutex_exit(&dnp->dn_lock);
7140 }
7141 
7142 static void
7143 exit_driver(struct devnames *dnp)
7144 {
7145 	mutex_enter(&dnp->dn_lock);
7146 	ASSERT(dnp->dn_busy_thread == curthread);
7147 	dnp->dn_flags &= ~DN_DRIVER_BUSY;
7148 	dnp->dn_busy_thread = NULL;
7149 	cv_broadcast(&dnp->dn_wait);
7150 	mutex_exit(&dnp->dn_lock);
7151 }
7152 
7153 struct dev_ops *
7154 ddi_hold_installed_driver(major_t major)
7155 {
7156 	struct dev_ops *ops;
7157 	struct devnames *dnp;
7158 	char *parents;
7159 	int error;
7160 
7161 	ops = ddi_hold_driver(major);
7162 	if (ops == NULL)
7163 		return (NULL);
7164 
7165 	/*
7166 	 * Return immediately if all the attach operations associated
7167 	 * with a ddi_hold_installed_driver() call have already been done.
7168 	 */
7169 	dnp = &devnamesp[major];
7170 	enter_driver(dnp);
7171 	if (dnp->dn_flags & DN_DRIVER_HELD) {
7172 		exit_driver(dnp);
7173 		if (i_ddi_devs_attached(major) == DDI_SUCCESS)
7174 			return (ops);
7175 		ddi_rele_driver(major);
7176 		return (NULL);
7177 	}
7178 
7179 	LOCK_DEV_OPS(&dnp->dn_lock);
7180 	dnp->dn_flags |= (DN_DRIVER_HELD | DN_NO_AUTODETACH);
7181 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7182 
7183 	DCOMPATPRINTF((CE_CONT,
7184 	    "ddi_hold_installed_driver: %s\n", dnp->dn_name));
7185 
7186 	/*
7187 	 * When the driver has no .conf children, it is sufficient
7188 	 * to attach existing nodes in the device tree. Nodes not
7189 	 * enumerated by the OBP are not attached.
7190 	 */
7191 	if (dnp->dn_pl == NULL) {
7192 		if (attach_driver_nodes(major) == DDI_SUCCESS) {
7193 			exit_driver(dnp);
7194 			return (ops);
7195 		}
7196 		exit_driver(dnp);
7197 		ddi_rele_driver(major);
7198 		return (NULL);
7199 	}
7200 
7201 	/*
7202 	 * Driver has .conf nodes. We find all possible parents
7203 	 * and recursively all ddi_hold_installed_driver on the
7204 	 * parent driver; then we invoke ndi_config_driver()
7205 	 * on all possible parent node in parallel to speed up
7206 	 * performance.
7207 	 */
7208 	parents = kmem_zalloc(devcnt * sizeof (char), KM_SLEEP);
7209 
7210 	LOCK_DEV_OPS(&dnp->dn_lock);
7211 	/* find .conf parents */
7212 	(void) impl_parlist_to_major(dnp->dn_pl, parents);
7213 	/* find hw node parents */
7214 	diplist_to_parent_major(dnp->dn_head, parents);
7215 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7216 
7217 	error = attach_driver_by_parent(major, parents);
7218 	kmem_free(parents, devcnt * sizeof (char));
7219 	if (error == DDI_SUCCESS) {
7220 		exit_driver(dnp);
7221 		return (ops);
7222 	}
7223 
7224 	exit_driver(dnp);
7225 	ddi_rele_driver(major);
7226 	return (NULL);
7227 }
7228 
7229 /*
7230  * Default bus_config entry point for nexus drivers
7231  */
7232 int
7233 ndi_busop_bus_config(dev_info_t *pdip, uint_t flags, ddi_bus_config_op_t op,
7234     void *arg, dev_info_t **child, clock_t timeout)
7235 {
7236 	major_t major;
7237 
7238 	/*
7239 	 * A timeout of 30 minutes or more is probably a mistake
7240 	 * This is intended to catch uses where timeout is in
7241 	 * the wrong units.  timeout must be in units of ticks.
7242 	 */
7243 	ASSERT(timeout < SEC_TO_TICK(1800));
7244 
7245 	major = DDI_MAJOR_T_NONE;
7246 	switch (op) {
7247 	case BUS_CONFIG_ONE:
7248 		NDI_DEBUG(flags, (CE_CONT, "%s%d: bus config %s timeout=%ld\n",
7249 		    ddi_driver_name(pdip), ddi_get_instance(pdip),
7250 		    (char *)arg, timeout));
7251 		return (devi_config_one(pdip, (char *)arg, child, flags,
7252 		    timeout));
7253 
7254 	case BUS_CONFIG_DRIVER:
7255 		major = (major_t)(uintptr_t)arg;
7256 		/*FALLTHROUGH*/
7257 	case BUS_CONFIG_ALL:
7258 		NDI_DEBUG(flags, (CE_CONT, "%s%d: bus config timeout=%ld\n",
7259 		    ddi_driver_name(pdip), ddi_get_instance(pdip),
7260 		    timeout));
7261 		if (timeout > 0) {
7262 			NDI_DEBUG(flags, (CE_CONT,
7263 			    "%s%d: bus config all timeout=%ld\n",
7264 			    ddi_driver_name(pdip), ddi_get_instance(pdip),
7265 			    timeout));
7266 			delay(timeout);
7267 		}
7268 		return (config_immediate_children(pdip, flags, major));
7269 
7270 	default:
7271 		return (NDI_FAILURE);
7272 	}
7273 	/*NOTREACHED*/
7274 }
7275 
7276 /*
7277  * Default busop bus_unconfig handler for nexus drivers
7278  */
7279 int
7280 ndi_busop_bus_unconfig(dev_info_t *pdip, uint_t flags, ddi_bus_config_op_t op,
7281     void *arg)
7282 {
7283 	major_t major;
7284 
7285 	major = DDI_MAJOR_T_NONE;
7286 	switch (op) {
7287 	case BUS_UNCONFIG_ONE:
7288 		NDI_DEBUG(flags, (CE_CONT, "%s%d: bus unconfig %s\n",
7289 		    ddi_driver_name(pdip), ddi_get_instance(pdip),
7290 		    (char *)arg));
7291 		return (devi_unconfig_one(pdip, (char *)arg, flags));
7292 
7293 	case BUS_UNCONFIG_DRIVER:
7294 		major = (major_t)(uintptr_t)arg;
7295 		/*FALLTHROUGH*/
7296 	case BUS_UNCONFIG_ALL:
7297 		NDI_DEBUG(flags, (CE_CONT, "%s%d: bus unconfig all\n",
7298 		    ddi_driver_name(pdip), ddi_get_instance(pdip)));
7299 		return (unconfig_immediate_children(pdip, NULL, flags, major));
7300 
7301 	default:
7302 		return (NDI_FAILURE);
7303 	}
7304 	/*NOTREACHED*/
7305 }
7306 
7307 /*
7308  * dummy functions to be removed
7309  */
7310 void
7311 impl_rem_dev_props(dev_info_t *dip)
7312 {
7313 	_NOTE(ARGUNUSED(dip))
7314 	/* do nothing */
7315 }
7316 
7317 /*
7318  * Determine if a node is a leaf node. If not sure, return false (0).
7319  */
7320 static int
7321 is_leaf_node(dev_info_t *dip)
7322 {
7323 	major_t major = ddi_driver_major(dip);
7324 
7325 	if (major == DDI_MAJOR_T_NONE)
7326 		return (0);
7327 
7328 	return (devnamesp[major].dn_flags & DN_LEAF_DRIVER);
7329 }
7330 
7331 /*
7332  * Multithreaded [un]configuration
7333  */
7334 static struct mt_config_handle *
7335 mt_config_init(dev_info_t *pdip, dev_info_t **dipp, int flags,
7336     major_t major, int op, struct brevq_node **brevqp)
7337 {
7338 	struct mt_config_handle	*hdl = kmem_alloc(sizeof (*hdl), KM_SLEEP);
7339 
7340 	mutex_init(&hdl->mtc_lock, NULL, MUTEX_DEFAULT, NULL);
7341 	cv_init(&hdl->mtc_cv, NULL, CV_DEFAULT, NULL);
7342 	hdl->mtc_pdip = pdip;
7343 	hdl->mtc_fdip = dipp;
7344 	hdl->mtc_parmajor = DDI_MAJOR_T_NONE;
7345 	hdl->mtc_flags = flags;
7346 	hdl->mtc_major = major;
7347 	hdl->mtc_thr_count = 0;
7348 	hdl->mtc_op = op;
7349 	hdl->mtc_error = 0;
7350 	hdl->mtc_brevqp = brevqp;
7351 
7352 #ifdef DEBUG
7353 	gethrestime(&hdl->start_time);
7354 	hdl->total_time = 0;
7355 #endif /* DEBUG */
7356 
7357 	return (hdl);
7358 }
7359 
7360 #ifdef DEBUG
7361 static int
7362 time_diff_in_msec(timestruc_t start, timestruc_t end)
7363 {
7364 	int	nsec, sec;
7365 
7366 	sec = end.tv_sec - start.tv_sec;
7367 	nsec = end.tv_nsec - start.tv_nsec;
7368 	if (nsec < 0) {
7369 		nsec += NANOSEC;
7370 		sec -= 1;
7371 	}
7372 
7373 	return (sec * (NANOSEC >> 20) + (nsec >> 20));
7374 }
7375 
7376 #endif	/* DEBUG */
7377 
7378 static int
7379 mt_config_fini(struct mt_config_handle *hdl)
7380 {
7381 	int		rv;
7382 #ifdef DEBUG
7383 	int		real_time;
7384 	timestruc_t	end_time;
7385 #endif /* DEBUG */
7386 
7387 	mutex_enter(&hdl->mtc_lock);
7388 	while (hdl->mtc_thr_count > 0)
7389 		cv_wait(&hdl->mtc_cv, &hdl->mtc_lock);
7390 	rv = hdl->mtc_error;
7391 	mutex_exit(&hdl->mtc_lock);
7392 
7393 #ifdef DEBUG
7394 	gethrestime(&end_time);
7395 	real_time = time_diff_in_msec(hdl->start_time, end_time);
7396 	if ((ddidebug & DDI_MTCONFIG) && hdl->mtc_pdip)
7397 		cmn_err(CE_NOTE,
7398 		    "config %s%d: total time %d msec, real time %d msec",
7399 		    ddi_driver_name(hdl->mtc_pdip),
7400 		    ddi_get_instance(hdl->mtc_pdip),
7401 		    hdl->total_time, real_time);
7402 #endif /* DEBUG */
7403 
7404 	cv_destroy(&hdl->mtc_cv);
7405 	mutex_destroy(&hdl->mtc_lock);
7406 	kmem_free(hdl, sizeof (*hdl));
7407 
7408 	return (rv);
7409 }
7410 
7411 struct mt_config_data {
7412 	struct mt_config_handle	*mtc_hdl;
7413 	dev_info_t		*mtc_dip;
7414 	major_t			mtc_major;
7415 	int			mtc_flags;
7416 	struct brevq_node	*mtc_brn;
7417 	struct mt_config_data	*mtc_next;
7418 };
7419 
7420 static void
7421 mt_config_thread(void *arg)
7422 {
7423 	struct mt_config_data	*mcd = (struct mt_config_data *)arg;
7424 	struct mt_config_handle	*hdl = mcd->mtc_hdl;
7425 	dev_info_t		*dip = mcd->mtc_dip;
7426 	dev_info_t		*rdip, **dipp;
7427 	major_t			major = mcd->mtc_major;
7428 	int			flags = mcd->mtc_flags;
7429 	int			rv = 0;
7430 
7431 #ifdef DEBUG
7432 	timestruc_t start_time, end_time;
7433 	gethrestime(&start_time);
7434 #endif /* DEBUG */
7435 
7436 	rdip = NULL;
7437 	dipp = hdl->mtc_fdip ? &rdip : NULL;
7438 
7439 	switch (hdl->mtc_op) {
7440 	case MT_CONFIG_OP:
7441 		rv = devi_config_common(dip, flags, major);
7442 		break;
7443 	case MT_UNCONFIG_OP:
7444 		if (mcd->mtc_brn) {
7445 			struct brevq_node *brevq = NULL;
7446 			rv = devi_unconfig_common(dip, dipp, flags, major,
7447 			    &brevq);
7448 			mcd->mtc_brn->brn_child = brevq;
7449 		} else
7450 			rv = devi_unconfig_common(dip, dipp, flags, major,
7451 			    NULL);
7452 		break;
7453 	}
7454 
7455 	mutex_enter(&hdl->mtc_lock);
7456 #ifdef DEBUG
7457 	gethrestime(&end_time);
7458 	hdl->total_time += time_diff_in_msec(start_time, end_time);
7459 #endif /* DEBUG */
7460 
7461 	if ((rv != NDI_SUCCESS) && (hdl->mtc_error == 0)) {
7462 		hdl->mtc_error = rv;
7463 #ifdef	DEBUG
7464 		if ((ddidebug & DDI_DEBUG) && (major != DDI_MAJOR_T_NONE)) {
7465 			char	*path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
7466 
7467 			(void) ddi_pathname(dip, path);
7468 			cmn_err(CE_NOTE, "mt_config_thread: "
7469 			    "op %d.%d.%x at %s failed %d",
7470 			    hdl->mtc_op, major, flags, path, rv);
7471 			kmem_free(path, MAXPATHLEN);
7472 		}
7473 #endif	/* DEBUG */
7474 	}
7475 
7476 	if (hdl->mtc_fdip && *hdl->mtc_fdip == NULL) {
7477 		*hdl->mtc_fdip = rdip;
7478 		rdip = NULL;
7479 	}
7480 
7481 	if (rdip) {
7482 		ASSERT(rv != NDI_SUCCESS);
7483 		ndi_rele_devi(rdip);
7484 	}
7485 
7486 	ndi_rele_devi(dip);
7487 
7488 	if (--hdl->mtc_thr_count == 0)
7489 		cv_broadcast(&hdl->mtc_cv);
7490 	mutex_exit(&hdl->mtc_lock);
7491 	kmem_free(mcd, sizeof (*mcd));
7492 }
7493 
7494 /*
7495  * Multi-threaded config/unconfig of child nexus
7496  */
7497 static void
7498 mt_config_children(struct mt_config_handle *hdl)
7499 {
7500 	dev_info_t		*pdip = hdl->mtc_pdip;
7501 	major_t			major = hdl->mtc_major;
7502 	dev_info_t		*dip;
7503 	int			circ;
7504 	struct brevq_node	*brn;
7505 	struct mt_config_data	*mcd_head = NULL;
7506 	struct mt_config_data	*mcd_tail = NULL;
7507 	struct mt_config_data	*mcd;
7508 #ifdef DEBUG
7509 	timestruc_t		end_time;
7510 
7511 	/* Update total_time in handle */
7512 	gethrestime(&end_time);
7513 	hdl->total_time += time_diff_in_msec(hdl->start_time, end_time);
7514 #endif
7515 
7516 	ndi_devi_enter(pdip, &circ);
7517 	dip = ddi_get_child(pdip);
7518 	while (dip) {
7519 		if (hdl->mtc_op == MT_UNCONFIG_OP && hdl->mtc_brevqp &&
7520 		    !(DEVI_EVREMOVE(dip)) &&
7521 		    i_ddi_node_state(dip) >= DS_INITIALIZED) {
7522 			/*
7523 			 * Enqueue this dip's deviname.
7524 			 * No need to hold a lock while enqueuing since this
7525 			 * is the only thread doing the enqueue and no one
7526 			 * walks the queue while we are in multithreaded
7527 			 * unconfiguration.
7528 			 */
7529 			brn = brevq_enqueue(hdl->mtc_brevqp, dip, NULL);
7530 		} else
7531 			brn = NULL;
7532 
7533 		/*
7534 		 * Hold the child that we are processing so he does not get
7535 		 * removed. The corrisponding ndi_rele_devi() for children
7536 		 * that are not being skipped is done at the end of
7537 		 * mt_config_thread().
7538 		 */
7539 		ndi_hold_devi(dip);
7540 
7541 		/*
7542 		 * skip leaf nodes and (for configure) nodes not
7543 		 * fully attached.
7544 		 */
7545 		if (is_leaf_node(dip) ||
7546 		    (hdl->mtc_op == MT_CONFIG_OP &&
7547 		    i_ddi_node_state(dip) < DS_READY)) {
7548 			ndi_rele_devi(dip);
7549 			dip = ddi_get_next_sibling(dip);
7550 			continue;
7551 		}
7552 
7553 		mcd = kmem_alloc(sizeof (*mcd), KM_SLEEP);
7554 		mcd->mtc_dip = dip;
7555 		mcd->mtc_hdl = hdl;
7556 		mcd->mtc_brn = brn;
7557 
7558 		/*
7559 		 * Switch a 'driver' operation to an 'all' operation below a
7560 		 * node bound to the driver.
7561 		 */
7562 		if ((major == DDI_MAJOR_T_NONE) ||
7563 		    (major == ddi_driver_major(dip)))
7564 			mcd->mtc_major = DDI_MAJOR_T_NONE;
7565 		else
7566 			mcd->mtc_major = major;
7567 
7568 		/*
7569 		 * The unconfig-driver to unconfig-all conversion above
7570 		 * constitutes an autodetach for NDI_DETACH_DRIVER calls,
7571 		 * set NDI_AUTODETACH.
7572 		 */
7573 		mcd->mtc_flags = hdl->mtc_flags;
7574 		if ((mcd->mtc_flags & NDI_DETACH_DRIVER) &&
7575 		    (hdl->mtc_op == MT_UNCONFIG_OP) &&
7576 		    (major == ddi_driver_major(pdip)))
7577 			mcd->mtc_flags |= NDI_AUTODETACH;
7578 
7579 		mutex_enter(&hdl->mtc_lock);
7580 		hdl->mtc_thr_count++;
7581 		mutex_exit(&hdl->mtc_lock);
7582 
7583 		/*
7584 		 * Add to end of list to process after ndi_devi_exit to avoid
7585 		 * locking differences depending on value of mtc_off.
7586 		 */
7587 		mcd->mtc_next = NULL;
7588 		if (mcd_head == NULL)
7589 			mcd_head = mcd;
7590 		else
7591 			mcd_tail->mtc_next = mcd;
7592 		mcd_tail = mcd;
7593 
7594 		dip = ddi_get_next_sibling(dip);
7595 	}
7596 	ndi_devi_exit(pdip, circ);
7597 
7598 	/* go through the list of held children */
7599 	for (mcd = mcd_head; mcd; mcd = mcd_head) {
7600 		mcd_head = mcd->mtc_next;
7601 		if (mtc_off || (mcd->mtc_flags & NDI_MTC_OFF))
7602 			mt_config_thread(mcd);
7603 		else
7604 			(void) thread_create(NULL, 0, mt_config_thread, mcd,
7605 			    0, &p0, TS_RUN, minclsyspri);
7606 	}
7607 }
7608 
7609 static void
7610 mt_config_driver(struct mt_config_handle *hdl)
7611 {
7612 	major_t			par_major = hdl->mtc_parmajor;
7613 	major_t			major = hdl->mtc_major;
7614 	struct devnames		*dnp = &devnamesp[par_major];
7615 	dev_info_t		*dip;
7616 	struct mt_config_data	*mcd_head = NULL;
7617 	struct mt_config_data	*mcd_tail = NULL;
7618 	struct mt_config_data	*mcd;
7619 #ifdef DEBUG
7620 	timestruc_t		end_time;
7621 
7622 	/* Update total_time in handle */
7623 	gethrestime(&end_time);
7624 	hdl->total_time += time_diff_in_msec(hdl->start_time, end_time);
7625 #endif
7626 	ASSERT(par_major != DDI_MAJOR_T_NONE);
7627 	ASSERT(major != DDI_MAJOR_T_NONE);
7628 
7629 	LOCK_DEV_OPS(&dnp->dn_lock);
7630 	dip = devnamesp[par_major].dn_head;
7631 	while (dip) {
7632 		/*
7633 		 * Hold the child that we are processing so he does not get
7634 		 * removed. The corrisponding ndi_rele_devi() for children
7635 		 * that are not being skipped is done at the end of
7636 		 * mt_config_thread().
7637 		 */
7638 		ndi_hold_devi(dip);
7639 
7640 		/* skip leaf nodes and nodes not fully attached */
7641 		if (!i_ddi_devi_attached(dip) || is_leaf_node(dip)) {
7642 			ndi_rele_devi(dip);
7643 			dip = ddi_get_next(dip);
7644 			continue;
7645 		}
7646 
7647 		mcd = kmem_alloc(sizeof (*mcd), KM_SLEEP);
7648 		mcd->mtc_dip = dip;
7649 		mcd->mtc_hdl = hdl;
7650 		mcd->mtc_major = major;
7651 		mcd->mtc_flags = hdl->mtc_flags;
7652 
7653 		mutex_enter(&hdl->mtc_lock);
7654 		hdl->mtc_thr_count++;
7655 		mutex_exit(&hdl->mtc_lock);
7656 
7657 		/*
7658 		 * Add to end of list to process after UNLOCK_DEV_OPS to avoid
7659 		 * locking differences depending on value of mtc_off.
7660 		 */
7661 		mcd->mtc_next = NULL;
7662 		if (mcd_head == NULL)
7663 			mcd_head = mcd;
7664 		else
7665 			mcd_tail->mtc_next = mcd;
7666 		mcd_tail = mcd;
7667 
7668 		dip = ddi_get_next(dip);
7669 	}
7670 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7671 
7672 	/* go through the list of held children */
7673 	for (mcd = mcd_head; mcd; mcd = mcd_head) {
7674 		mcd_head = mcd->mtc_next;
7675 		if (mtc_off || (mcd->mtc_flags & NDI_MTC_OFF))
7676 			mt_config_thread(mcd);
7677 		else
7678 			(void) thread_create(NULL, 0, mt_config_thread, mcd,
7679 			    0, &p0, TS_RUN, minclsyspri);
7680 	}
7681 }
7682 
7683 /*
7684  * Given the nodeid for a persistent (PROM or SID) node, return
7685  * the corresponding devinfo node
7686  * NOTE: This function will return NULL for .conf nodeids.
7687  */
7688 dev_info_t *
7689 e_ddi_nodeid_to_dip(pnode_t nodeid)
7690 {
7691 	dev_info_t		*dip = NULL;
7692 	struct devi_nodeid	*prev, *elem;
7693 
7694 	mutex_enter(&devimap->dno_lock);
7695 
7696 	prev = NULL;
7697 	for (elem = devimap->dno_head; elem; elem = elem->next) {
7698 		if (elem->nodeid == nodeid) {
7699 			ndi_hold_devi(elem->dip);
7700 			dip = elem->dip;
7701 			break;
7702 		}
7703 		prev = elem;
7704 	}
7705 
7706 	/*
7707 	 * Move to head for faster lookup next time
7708 	 */
7709 	if (elem && prev) {
7710 		prev->next = elem->next;
7711 		elem->next = devimap->dno_head;
7712 		devimap->dno_head = elem;
7713 	}
7714 
7715 	mutex_exit(&devimap->dno_lock);
7716 	return (dip);
7717 }
7718 
7719 static void
7720 free_cache_task(void *arg)
7721 {
7722 	ASSERT(arg == NULL);
7723 
7724 	mutex_enter(&di_cache.cache_lock);
7725 
7726 	/*
7727 	 * The cache can be invalidated without holding the lock
7728 	 * but it can be made valid again only while the lock is held.
7729 	 * So if the cache is invalid when the lock is held, it will
7730 	 * stay invalid until lock is released.
7731 	 */
7732 	if (!di_cache.cache_valid)
7733 		i_ddi_di_cache_free(&di_cache);
7734 
7735 	mutex_exit(&di_cache.cache_lock);
7736 
7737 	if (di_cache_debug)
7738 		cmn_err(CE_NOTE, "system_taskq: di_cache freed");
7739 }
7740 
7741 extern int modrootloaded;
7742 
7743 void
7744 i_ddi_di_cache_free(struct di_cache *cache)
7745 {
7746 	int	error;
7747 	extern int sys_shutdown;
7748 
7749 	ASSERT(mutex_owned(&cache->cache_lock));
7750 
7751 	if (cache->cache_size) {
7752 		ASSERT(cache->cache_size > 0);
7753 		ASSERT(cache->cache_data);
7754 
7755 		kmem_free(cache->cache_data, cache->cache_size);
7756 		cache->cache_data = NULL;
7757 		cache->cache_size = 0;
7758 
7759 		if (di_cache_debug)
7760 			cmn_err(CE_NOTE, "i_ddi_di_cache_free: freed cachemem");
7761 	} else {
7762 		ASSERT(cache->cache_data == NULL);
7763 		if (di_cache_debug)
7764 			cmn_err(CE_NOTE, "i_ddi_di_cache_free: NULL cache");
7765 	}
7766 
7767 	if (!modrootloaded || rootvp == NULL ||
7768 	    vn_is_readonly(rootvp) || sys_shutdown) {
7769 		if (di_cache_debug) {
7770 			cmn_err(CE_WARN, "/ not mounted/RDONLY. Skip unlink");
7771 		}
7772 		return;
7773 	}
7774 
7775 	error = vn_remove(DI_CACHE_FILE, UIO_SYSSPACE, RMFILE);
7776 	if (di_cache_debug && error && error != ENOENT) {
7777 		cmn_err(CE_WARN, "%s: unlink failed: %d", DI_CACHE_FILE, error);
7778 	} else if (di_cache_debug && !error) {
7779 		cmn_err(CE_NOTE, "i_ddi_di_cache_free: unlinked cache file");
7780 	}
7781 }
7782 
7783 void
7784 i_ddi_di_cache_invalidate()
7785 {
7786 	int	cache_valid;
7787 
7788 	if (!modrootloaded || !i_ddi_io_initialized()) {
7789 		if (di_cache_debug)
7790 			cmn_err(CE_NOTE, "I/O not inited. Skipping invalidate");
7791 		return;
7792 	}
7793 
7794 	/* Increment devtree generation number. */
7795 	atomic_inc_ulong(&devtree_gen);
7796 
7797 	/* Invalidate the in-core cache and dispatch free on valid->invalid */
7798 	cache_valid = atomic_swap_uint(&di_cache.cache_valid, 0);
7799 	if (cache_valid) {
7800 		/*
7801 		 * This is an optimization to start cleaning up a cached
7802 		 * snapshot early.  For this reason, it is OK for
7803 		 * taskq_dispatach to fail (and it is OK to not track calling
7804 		 * context relative to sleep, and assume NOSLEEP).
7805 		 */
7806 		(void) taskq_dispatch(system_taskq, free_cache_task, NULL,
7807 		    TQ_NOSLEEP);
7808 	}
7809 
7810 	if (di_cache_debug) {
7811 		cmn_err(CE_NOTE, "invalidation");
7812 	}
7813 }
7814 
7815 
7816 static void
7817 i_bind_vhci_node(dev_info_t *dip)
7818 {
7819 	DEVI(dip)->devi_major = ddi_name_to_major(ddi_node_name(dip));
7820 	i_ddi_set_node_state(dip, DS_BOUND);
7821 }
7822 
7823 static char vhci_node_addr[2];
7824 
7825 static int
7826 i_init_vhci_node(dev_info_t *dip)
7827 {
7828 	add_global_props(dip);
7829 	DEVI(dip)->devi_ops = ndi_hold_driver(dip);
7830 	if (DEVI(dip)->devi_ops == NULL)
7831 		return (-1);
7832 
7833 	DEVI(dip)->devi_instance = e_ddi_assign_instance(dip);
7834 	e_ddi_keep_instance(dip);
7835 	vhci_node_addr[0]	= '\0';
7836 	ddi_set_name_addr(dip, vhci_node_addr);
7837 	i_ddi_set_node_state(dip, DS_INITIALIZED);
7838 	return (0);
7839 }
7840 
7841 static void
7842 i_link_vhci_node(dev_info_t *dip)
7843 {
7844 	ASSERT(MUTEX_HELD(&global_vhci_lock));
7845 
7846 	/*
7847 	 * scsi_vhci should be kept left most of the device tree.
7848 	 */
7849 	if (scsi_vhci_dip) {
7850 		DEVI(dip)->devi_sibling = DEVI(scsi_vhci_dip)->devi_sibling;
7851 		DEVI(scsi_vhci_dip)->devi_sibling = DEVI(dip);
7852 	} else {
7853 		DEVI(dip)->devi_sibling = DEVI(top_devinfo)->devi_child;
7854 		DEVI(top_devinfo)->devi_child = DEVI(dip);
7855 	}
7856 }
7857 
7858 
7859 /*
7860  * This a special routine to enumerate vhci node (child of rootnex
7861  * node) without holding the ndi_devi_enter() lock. The device node
7862  * is allocated, initialized and brought into DS_READY state before
7863  * inserting into the device tree. The VHCI node is handcrafted
7864  * here to bring the node to DS_READY, similar to rootnex node.
7865  *
7866  * The global_vhci_lock protects linking the node into the device
7867  * as same lock is held before linking/unlinking any direct child
7868  * of rootnex children.
7869  *
7870  * This routine is a workaround to handle a possible deadlock
7871  * that occurs while trying to enumerate node in a different sub-tree
7872  * during _init/_attach entry points.
7873  */
7874 /*ARGSUSED*/
7875 dev_info_t *
7876 ndi_devi_config_vhci(char *drvname, int flags)
7877 {
7878 	struct devnames		*dnp;
7879 	dev_info_t		*dip;
7880 	major_t			major = ddi_name_to_major(drvname);
7881 
7882 	if (major == -1)
7883 		return (NULL);
7884 
7885 	/* Make sure we create the VHCI node only once */
7886 	dnp = &devnamesp[major];
7887 	LOCK_DEV_OPS(&dnp->dn_lock);
7888 	if (dnp->dn_head) {
7889 		dip = dnp->dn_head;
7890 		UNLOCK_DEV_OPS(&dnp->dn_lock);
7891 		return (dip);
7892 	}
7893 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7894 
7895 	/* Allocate the VHCI node */
7896 	ndi_devi_alloc_sleep(top_devinfo, drvname, DEVI_SID_NODEID, &dip);
7897 	ndi_hold_devi(dip);
7898 
7899 	/* Mark the node as VHCI */
7900 	DEVI(dip)->devi_node_attributes |= DDI_VHCI_NODE;
7901 
7902 	i_ddi_add_devimap(dip);
7903 	i_bind_vhci_node(dip);
7904 	if (i_init_vhci_node(dip) == -1) {
7905 		ndi_rele_devi(dip);
7906 		(void) ndi_devi_free(dip);
7907 		return (NULL);
7908 	}
7909 
7910 	mutex_enter(&(DEVI(dip)->devi_lock));
7911 	DEVI_SET_ATTACHING(dip);
7912 	mutex_exit(&(DEVI(dip)->devi_lock));
7913 
7914 	if (devi_attach(dip, DDI_ATTACH) != DDI_SUCCESS) {
7915 		cmn_err(CE_CONT, "Could not attach %s driver", drvname);
7916 		e_ddi_free_instance(dip, vhci_node_addr);
7917 		ndi_rele_devi(dip);
7918 		(void) ndi_devi_free(dip);
7919 		return (NULL);
7920 	}
7921 	mutex_enter(&(DEVI(dip)->devi_lock));
7922 	DEVI_CLR_ATTACHING(dip);
7923 	mutex_exit(&(DEVI(dip)->devi_lock));
7924 
7925 	mutex_enter(&global_vhci_lock);
7926 	i_link_vhci_node(dip);
7927 	mutex_exit(&global_vhci_lock);
7928 	i_ddi_set_node_state(dip, DS_READY);
7929 
7930 	LOCK_DEV_OPS(&dnp->dn_lock);
7931 	dnp->dn_flags |= DN_DRIVER_HELD;
7932 	dnp->dn_head = dip;
7933 	UNLOCK_DEV_OPS(&dnp->dn_lock);
7934 
7935 	i_ndi_devi_report_status_change(dip, NULL);
7936 
7937 	return (dip);
7938 }
7939 
7940 /*
7941  * Maintain DEVI_DEVICE_REMOVED hotplug devi_state for remove/reinsert hotplug
7942  * of open devices. Currently, because of tight coupling between the devfs file
7943  * system and the Solaris device tree, a driver can't always make the device
7944  * tree state (esp devi_node_state) match device hardware hotplug state. Until
7945  * resolved, to overcome this deficiency we use the following interfaces that
7946  * maintain the DEVI_DEVICE_REMOVED devi_state status bit.  These interface
7947  * report current state, and drive operation (like events and cache
7948  * invalidation) when a driver changes remove/insert state of an open device.
7949  *
7950  * The ndi_devi_device_isremoved() returns 1 if the device is currently removed.
7951  *
7952  * The ndi_devi_device_remove() interface declares the device as removed, and
7953  * returns 1 if there was a state change associated with this declaration.
7954  *
7955  * The ndi_devi_device_insert() declares the device as inserted, and returns 1
7956  * if there was a state change associated with this declaration.
7957  */
7958 int
7959 ndi_devi_device_isremoved(dev_info_t *dip)
7960 {
7961 	return (DEVI_IS_DEVICE_REMOVED(dip));
7962 }
7963 
7964 int
7965 ndi_devi_device_remove(dev_info_t *dip)
7966 {
7967 	ASSERT(dip && ddi_get_parent(dip) &&
7968 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
7969 
7970 	/* Return if already marked removed. */
7971 	if (ndi_devi_device_isremoved(dip))
7972 		return (0);
7973 
7974 	/* Mark the device as having been physically removed. */
7975 	mutex_enter(&(DEVI(dip)->devi_lock));
7976 	ndi_devi_set_hidden(dip);	/* invisible: lookup/snapshot */
7977 	DEVI_SET_DEVICE_REMOVED(dip);
7978 	DEVI_SET_EVREMOVE(dip);		/* this clears EVADD too */
7979 	mutex_exit(&(DEVI(dip)->devi_lock));
7980 
7981 	/* report remove (as 'removed') */
7982 	i_ndi_devi_report_status_change(dip, NULL);
7983 
7984 	/*
7985 	 * Invalidate the cache to ensure accurate
7986 	 * (di_state() & DI_DEVICE_REMOVED).
7987 	 */
7988 	i_ddi_di_cache_invalidate();
7989 
7990 	/*
7991 	 * Generate sysevent for those interested in removal (either directly
7992 	 * via EC_DEVFS or indirectly via devfsadmd generated EC_DEV).
7993 	 */
7994 	i_ddi_log_devfs_device_remove(dip);
7995 
7996 	return (1);		/* DEVICE_REMOVED state changed */
7997 }
7998 
7999 int
8000 ndi_devi_device_insert(dev_info_t *dip)
8001 {
8002 	ASSERT(dip && ddi_get_parent(dip) &&
8003 	    DEVI_BUSY_OWNED(ddi_get_parent(dip)));
8004 
8005 	/* Return if not marked removed. */
8006 	if (!ndi_devi_device_isremoved(dip))
8007 		return (0);
8008 
8009 	/* Mark the device as having been physically reinserted. */
8010 	mutex_enter(&(DEVI(dip)->devi_lock));
8011 	ndi_devi_clr_hidden(dip);	/* visible: lookup/snapshot */
8012 	DEVI_SET_DEVICE_REINSERTED(dip);
8013 	DEVI_SET_EVADD(dip);		/* this clears EVREMOVE too */
8014 	mutex_exit(&(DEVI(dip)->devi_lock));
8015 
8016 	/* report insert (as 'online') */
8017 	i_ndi_devi_report_status_change(dip, NULL);
8018 
8019 	/*
8020 	 * Invalidate the cache to ensure accurate
8021 	 * (di_state() & DI_DEVICE_REMOVED).
8022 	 */
8023 	i_ddi_di_cache_invalidate();
8024 
8025 	/*
8026 	 * Generate sysevent for those interested in removal (either directly
8027 	 * via EC_DEVFS or indirectly via devfsadmd generated EC_DEV).
8028 	 */
8029 	i_ddi_log_devfs_device_insert(dip);
8030 
8031 	return (1);		/* DEVICE_REMOVED state changed */
8032 }
8033 
8034 /*
8035  * ibt_hw_is_present() returns 0 when there is no IB hardware actively
8036  * running.  This is primarily useful for modules like rpcmod which
8037  * needs a quick check to decide whether or not it should try to use
8038  * InfiniBand
8039  */
8040 int ib_hw_status = 0;
8041 int
8042 ibt_hw_is_present()
8043 {
8044 	return (ib_hw_status);
8045 }
8046 
8047 /*
8048  * ASSERT that constraint flag is not set and then set the "retire attempt"
8049  * flag.
8050  */
8051 int
8052 e_ddi_mark_retiring(dev_info_t *dip, void *arg)
8053 {
8054 	char	**cons_array = (char **)arg;
8055 	char	*path;
8056 	int	constraint;
8057 	int	i;
8058 
8059 	constraint = 0;
8060 	if (cons_array) {
8061 		path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8062 		(void) ddi_pathname(dip, path);
8063 		for (i = 0; cons_array[i] != NULL; i++) {
8064 			if (strcmp(path, cons_array[i]) == 0) {
8065 				constraint = 1;
8066 				break;
8067 			}
8068 		}
8069 		kmem_free(path, MAXPATHLEN);
8070 	}
8071 
8072 	mutex_enter(&DEVI(dip)->devi_lock);
8073 	ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT));
8074 	DEVI(dip)->devi_flags |= DEVI_RETIRING;
8075 	if (constraint)
8076 		DEVI(dip)->devi_flags |= DEVI_R_CONSTRAINT;
8077 	mutex_exit(&DEVI(dip)->devi_lock);
8078 
8079 	RIO_VERBOSE((CE_NOTE, "marked dip as undergoing retire process dip=%p",
8080 	    (void *)dip));
8081 
8082 	if (constraint)
8083 		RIO_DEBUG((CE_NOTE, "marked dip as constrained, dip=%p",
8084 		    (void *)dip));
8085 
8086 	if (MDI_PHCI(dip))
8087 		mdi_phci_mark_retiring(dip, cons_array);
8088 
8089 	return (DDI_WALK_CONTINUE);
8090 }
8091 
8092 static void
8093 free_array(char **cons_array)
8094 {
8095 	int	i;
8096 
8097 	if (cons_array == NULL)
8098 		return;
8099 
8100 	for (i = 0; cons_array[i] != NULL; i++) {
8101 		kmem_free(cons_array[i], strlen(cons_array[i]) + 1);
8102 	}
8103 	kmem_free(cons_array, (i+1) * sizeof (char *));
8104 }
8105 
8106 /*
8107  * Walk *every* node in subtree and check if it blocks, allows or has no
8108  * comment on a proposed retire.
8109  */
8110 int
8111 e_ddi_retire_notify(dev_info_t *dip, void *arg)
8112 {
8113 	int	*constraint = (int *)arg;
8114 
8115 	RIO_DEBUG((CE_NOTE, "retire notify: dip = %p", (void *)dip));
8116 
8117 	(void) e_ddi_offline_notify(dip);
8118 
8119 	mutex_enter(&(DEVI(dip)->devi_lock));
8120 	if (!(DEVI(dip)->devi_flags & DEVI_RETIRING)) {
8121 		RIO_DEBUG((CE_WARN, "retire notify: dip in retire "
8122 		    "subtree is not marked: dip = %p", (void *)dip));
8123 		*constraint = 0;
8124 	} else if (DEVI(dip)->devi_flags & DEVI_R_BLOCKED) {
8125 		ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT));
8126 		RIO_DEBUG((CE_NOTE, "retire notify: BLOCKED: dip = %p",
8127 		    (void *)dip));
8128 		*constraint = 0;
8129 	} else if (!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT)) {
8130 		RIO_DEBUG((CE_NOTE, "retire notify: NO CONSTRAINT: "
8131 		    "dip = %p", (void *)dip));
8132 		*constraint = 0;
8133 	} else {
8134 		RIO_DEBUG((CE_NOTE, "retire notify: CONSTRAINT set: "
8135 		    "dip = %p", (void *)dip));
8136 	}
8137 	mutex_exit(&DEVI(dip)->devi_lock);
8138 
8139 	if (MDI_PHCI(dip))
8140 		mdi_phci_retire_notify(dip, constraint);
8141 
8142 	return (DDI_WALK_CONTINUE);
8143 }
8144 
8145 int
8146 e_ddi_retire_finalize(dev_info_t *dip, void *arg)
8147 {
8148 	int constraint = *(int *)arg;
8149 	int finalize;
8150 	int phci_only;
8151 
8152 	ASSERT(DEVI_BUSY_OWNED(ddi_get_parent(dip)));
8153 
8154 	mutex_enter(&DEVI(dip)->devi_lock);
8155 	if (!(DEVI(dip)->devi_flags & DEVI_RETIRING)) {
8156 		RIO_DEBUG((CE_WARN,
8157 		    "retire: unmarked dip(%p) in retire subtree",
8158 		    (void *)dip));
8159 		ASSERT(!(DEVI(dip)->devi_flags & DEVI_RETIRED));
8160 		ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT));
8161 		ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_BLOCKED));
8162 		mutex_exit(&DEVI(dip)->devi_lock);
8163 		return (DDI_WALK_CONTINUE);
8164 	}
8165 
8166 	/*
8167 	 * retire the device if constraints have been applied
8168 	 * or if the device is not in use
8169 	 */
8170 	finalize = 0;
8171 	if (constraint) {
8172 		ASSERT(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT);
8173 		ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_BLOCKED));
8174 		DEVI(dip)->devi_flags &= ~DEVI_R_CONSTRAINT;
8175 		DEVI(dip)->devi_flags &= ~DEVI_RETIRING;
8176 		DEVI(dip)->devi_flags |= DEVI_RETIRED;
8177 		mutex_exit(&DEVI(dip)->devi_lock);
8178 		(void) spec_fence_snode(dip, NULL);
8179 		RIO_DEBUG((CE_NOTE, "Fenced off: dip = %p", (void *)dip));
8180 		e_ddi_offline_finalize(dip, DDI_SUCCESS);
8181 	} else {
8182 		if (DEVI(dip)->devi_flags & DEVI_R_BLOCKED) {
8183 			ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT));
8184 			DEVI(dip)->devi_flags &= ~DEVI_R_BLOCKED;
8185 			DEVI(dip)->devi_flags &= ~DEVI_RETIRING;
8186 			/* we have already finalized during notify */
8187 		} else if (DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT) {
8188 			DEVI(dip)->devi_flags &= ~DEVI_R_CONSTRAINT;
8189 			DEVI(dip)->devi_flags &= ~DEVI_RETIRING;
8190 			finalize = 1;
8191 		} else {
8192 			DEVI(dip)->devi_flags &= ~DEVI_RETIRING;
8193 			/*
8194 			 * even if no contracts, need to call finalize
8195 			 * to clear the contract barrier on the dip
8196 			 */
8197 			finalize = 1;
8198 		}
8199 		mutex_exit(&DEVI(dip)->devi_lock);
8200 		RIO_DEBUG((CE_NOTE, "finalize: NOT retired: dip = %p",
8201 		    (void *)dip));
8202 		if (finalize)
8203 			e_ddi_offline_finalize(dip, DDI_FAILURE);
8204 	}
8205 
8206 	/*
8207 	 * phci_only variable indicates no client checking, just
8208 	 * offline the PHCI. We set that to 0 to enable client
8209 	 * checking
8210 	 */
8211 	phci_only = 0;
8212 	if (MDI_PHCI(dip))
8213 		mdi_phci_retire_finalize(dip, phci_only);
8214 
8215 	return (DDI_WALK_CONTINUE);
8216 }
8217 
8218 /*
8219  * Returns
8220  *	DDI_SUCCESS if constraints allow retire
8221  *	DDI_FAILURE if constraints don't allow retire.
8222  * cons_array is a NULL terminated array of node paths for
8223  * which constraints have already been applied.
8224  */
8225 int
8226 e_ddi_retire_device(char *path, char **cons_array)
8227 {
8228 	dev_info_t	*dip;
8229 	dev_info_t	*pdip;
8230 	int		circ;
8231 	int		circ2;
8232 	int		constraint;
8233 	char		*devnm;
8234 
8235 	/*
8236 	 * First, lookup the device
8237 	 */
8238 	dip = e_ddi_hold_devi_by_path(path, 0);
8239 	if (dip == NULL) {
8240 		/*
8241 		 * device does not exist. This device cannot be
8242 		 * a critical device since it is not in use. Thus
8243 		 * this device is always retireable. Return DDI_SUCCESS
8244 		 * to indicate this. If this device is ever
8245 		 * instantiated, I/O framework will consult the
8246 		 * the persistent retire store, mark it as
8247 		 * retired and fence it off.
8248 		 */
8249 		RIO_DEBUG((CE_NOTE, "Retire device: device doesn't exist."
8250 		    " NOP. Just returning SUCCESS. path=%s", path));
8251 		free_array(cons_array);
8252 		return (DDI_SUCCESS);
8253 	}
8254 
8255 	RIO_DEBUG((CE_NOTE, "Retire device: found dip = %p.", (void *)dip));
8256 
8257 	pdip = ddi_get_parent(dip);
8258 	ndi_hold_devi(pdip);
8259 
8260 	/*
8261 	 * Run devfs_clean() in case dip has no constraints and is
8262 	 * not in use, so is retireable but there are dv_nodes holding
8263 	 * ref-count on the dip. Note that devfs_clean() always returns
8264 	 * success.
8265 	 */
8266 	devnm = kmem_alloc(MAXNAMELEN + 1, KM_SLEEP);
8267 	(void) ddi_deviname(dip, devnm);
8268 	(void) devfs_clean(pdip, devnm + 1, DV_CLEAN_FORCE);
8269 	kmem_free(devnm, MAXNAMELEN + 1);
8270 
8271 	ndi_devi_enter(pdip, &circ);
8272 
8273 	/* release hold from e_ddi_hold_devi_by_path */
8274 	ndi_rele_devi(dip);
8275 
8276 	/*
8277 	 * If it cannot make a determination, is_leaf_node() assumes
8278 	 * dip is a nexus.
8279 	 */
8280 	(void) e_ddi_mark_retiring(dip, cons_array);
8281 	if (!is_leaf_node(dip)) {
8282 		ndi_devi_enter(dip, &circ2);
8283 		ddi_walk_devs(ddi_get_child(dip), e_ddi_mark_retiring,
8284 		    cons_array);
8285 		ndi_devi_exit(dip, circ2);
8286 	}
8287 	free_array(cons_array);
8288 
8289 	/*
8290 	 * apply constraints
8291 	 */
8292 	RIO_DEBUG((CE_NOTE, "retire: subtree retire notify: path = %s", path));
8293 
8294 	constraint = 1;	/* assume constraints allow retire */
8295 	(void) e_ddi_retire_notify(dip, &constraint);
8296 	if (!is_leaf_node(dip)) {
8297 		ndi_devi_enter(dip, &circ2);
8298 		ddi_walk_devs(ddi_get_child(dip), e_ddi_retire_notify,
8299 		    &constraint);
8300 		ndi_devi_exit(dip, circ2);
8301 	}
8302 
8303 	/*
8304 	 * Now finalize the retire
8305 	 */
8306 	(void) e_ddi_retire_finalize(dip, &constraint);
8307 	if (!is_leaf_node(dip)) {
8308 		ndi_devi_enter(dip, &circ2);
8309 		ddi_walk_devs(ddi_get_child(dip), e_ddi_retire_finalize,
8310 		    &constraint);
8311 		ndi_devi_exit(dip, circ2);
8312 	}
8313 
8314 	if (!constraint) {
8315 		RIO_DEBUG((CE_WARN, "retire failed: path = %s", path));
8316 	} else {
8317 		RIO_DEBUG((CE_NOTE, "retire succeeded: path = %s", path));
8318 	}
8319 
8320 	ndi_devi_exit(pdip, circ);
8321 	ndi_rele_devi(pdip);
8322 	return (constraint ? DDI_SUCCESS : DDI_FAILURE);
8323 }
8324 
8325 static int
8326 unmark_and_unfence(dev_info_t *dip, void *arg)
8327 {
8328 	char	*path = (char *)arg;
8329 
8330 	ASSERT(path);
8331 
8332 	(void) ddi_pathname(dip, path);
8333 
8334 	mutex_enter(&DEVI(dip)->devi_lock);
8335 	DEVI(dip)->devi_flags &= ~DEVI_RETIRED;
8336 	DEVI_SET_DEVICE_ONLINE(dip);
8337 	mutex_exit(&DEVI(dip)->devi_lock);
8338 
8339 	RIO_VERBOSE((CE_NOTE, "Cleared RETIRED flag: dip=%p, path=%s",
8340 	    (void *)dip, path));
8341 
8342 	(void) spec_unfence_snode(dip);
8343 	RIO_DEBUG((CE_NOTE, "Unfenced device: %s", path));
8344 
8345 	if (MDI_PHCI(dip))
8346 		mdi_phci_unretire(dip);
8347 
8348 	return (DDI_WALK_CONTINUE);
8349 }
8350 
8351 struct find_dip {
8352 	char	*fd_buf;
8353 	char	*fd_path;
8354 	dev_info_t *fd_dip;
8355 };
8356 
8357 static int
8358 find_dip_fcn(dev_info_t *dip, void *arg)
8359 {
8360 	struct find_dip *findp = (struct find_dip *)arg;
8361 
8362 	(void) ddi_pathname(dip, findp->fd_buf);
8363 
8364 	if (strcmp(findp->fd_path, findp->fd_buf) != 0)
8365 		return (DDI_WALK_CONTINUE);
8366 
8367 	ndi_hold_devi(dip);
8368 	findp->fd_dip = dip;
8369 
8370 	return (DDI_WALK_TERMINATE);
8371 }
8372 
8373 int
8374 e_ddi_unretire_device(char *path)
8375 {
8376 	int		circ;
8377 	int		circ2;
8378 	char		*path2;
8379 	dev_info_t	*pdip;
8380 	dev_info_t	*dip;
8381 	struct find_dip	 find_dip;
8382 
8383 	ASSERT(path);
8384 	ASSERT(*path == '/');
8385 
8386 	if (strcmp(path, "/") == 0) {
8387 		cmn_err(CE_WARN, "Root node cannot be retired. Skipping "
8388 		    "device unretire: %s", path);
8389 		return (0);
8390 	}
8391 
8392 	/*
8393 	 * We can't lookup the dip (corresponding to path) via
8394 	 * e_ddi_hold_devi_by_path() because the dip may be offline
8395 	 * and may not attach. Use ddi_walk_devs() instead;
8396 	 */
8397 	find_dip.fd_buf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8398 	find_dip.fd_path = path;
8399 	find_dip.fd_dip = NULL;
8400 
8401 	pdip = ddi_root_node();
8402 
8403 	ndi_devi_enter(pdip, &circ);
8404 	ddi_walk_devs(ddi_get_child(pdip), find_dip_fcn, &find_dip);
8405 	ndi_devi_exit(pdip, circ);
8406 
8407 	kmem_free(find_dip.fd_buf, MAXPATHLEN);
8408 
8409 	if (find_dip.fd_dip == NULL) {
8410 		cmn_err(CE_WARN, "Device not found in device tree. Skipping "
8411 		    "device unretire: %s", path);
8412 		return (0);
8413 	}
8414 
8415 	dip = find_dip.fd_dip;
8416 
8417 	pdip = ddi_get_parent(dip);
8418 
8419 	ndi_hold_devi(pdip);
8420 
8421 	ndi_devi_enter(pdip, &circ);
8422 
8423 	path2 = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8424 
8425 	(void) unmark_and_unfence(dip, path2);
8426 	if (!is_leaf_node(dip)) {
8427 		ndi_devi_enter(dip, &circ2);
8428 		ddi_walk_devs(ddi_get_child(dip), unmark_and_unfence, path2);
8429 		ndi_devi_exit(dip, circ2);
8430 	}
8431 
8432 	kmem_free(path2, MAXPATHLEN);
8433 
8434 	/* release hold from find_dip_fcn() */
8435 	ndi_rele_devi(dip);
8436 
8437 	ndi_devi_exit(pdip, circ);
8438 
8439 	ndi_rele_devi(pdip);
8440 
8441 	return (0);
8442 }
8443 
8444 /*
8445  * Called before attach on a dip that has been retired.
8446  */
8447 static int
8448 mark_and_fence(dev_info_t *dip, void *arg)
8449 {
8450 	char    *fencepath = (char *)arg;
8451 
8452 	/*
8453 	 * We have already decided to retire this device. The various
8454 	 * constraint checking should not be set.
8455 	 * NOTE that the retire flag may already be set due to
8456 	 * fenced -> detach -> fenced transitions.
8457 	 */
8458 	mutex_enter(&DEVI(dip)->devi_lock);
8459 	ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_CONSTRAINT));
8460 	ASSERT(!(DEVI(dip)->devi_flags & DEVI_R_BLOCKED));
8461 	ASSERT(!(DEVI(dip)->devi_flags & DEVI_RETIRING));
8462 	DEVI(dip)->devi_flags |= DEVI_RETIRED;
8463 	mutex_exit(&DEVI(dip)->devi_lock);
8464 	RIO_VERBOSE((CE_NOTE, "marked as RETIRED dip=%p", (void *)dip));
8465 
8466 	if (fencepath) {
8467 		(void) spec_fence_snode(dip, NULL);
8468 		RIO_DEBUG((CE_NOTE, "Fenced: %s",
8469 		    ddi_pathname(dip, fencepath)));
8470 	}
8471 
8472 	return (DDI_WALK_CONTINUE);
8473 }
8474 
8475 /*
8476  * Checks the retire database and:
8477  *
8478  * - if device is present in the retire database, marks the device retired
8479  *   and fences it off.
8480  * - if device is not in retire database, allows the device to attach normally
8481  *
8482  * To be called only by framework attach code on first attach attempt.
8483  *
8484  */
8485 static void
8486 i_ddi_check_retire(dev_info_t *dip)
8487 {
8488 	char		*path;
8489 	dev_info_t	*pdip;
8490 	int		circ;
8491 	int		phci_only;
8492 
8493 	pdip = ddi_get_parent(dip);
8494 
8495 	/*
8496 	 * Root dip is treated special and doesn't take this code path.
8497 	 * Also root can never be retired.
8498 	 */
8499 	ASSERT(pdip);
8500 	ASSERT(DEVI_BUSY_OWNED(pdip));
8501 	ASSERT(i_ddi_node_state(dip) < DS_ATTACHED);
8502 
8503 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8504 
8505 	(void) ddi_pathname(dip, path);
8506 
8507 	RIO_VERBOSE((CE_NOTE, "Checking if dip should attach: dip=%p, path=%s",
8508 	    (void *)dip, path));
8509 
8510 	/*
8511 	 * Check if this device is in the "retired" store i.e.  should
8512 	 * be retired. If not, we have nothing to do.
8513 	 */
8514 	if (e_ddi_device_retired(path) == 0) {
8515 		RIO_VERBOSE((CE_NOTE, "device is NOT retired: path=%s", path));
8516 		kmem_free(path, MAXPATHLEN);
8517 		return;
8518 	}
8519 
8520 	RIO_DEBUG((CE_NOTE, "attach: device is retired: path=%s", path));
8521 
8522 	/*
8523 	 * Mark dips and fence off snodes (if any)
8524 	 */
8525 	RIO_DEBUG((CE_NOTE, "attach: Mark and fence subtree: path=%s", path));
8526 	(void) mark_and_fence(dip, path);
8527 	if (!is_leaf_node(dip)) {
8528 		ndi_devi_enter(dip, &circ);
8529 		ddi_walk_devs(ddi_get_child(dip), mark_and_fence, path);
8530 		ndi_devi_exit(dip, circ);
8531 	}
8532 
8533 	kmem_free(path, MAXPATHLEN);
8534 
8535 	/*
8536 	 * We don't want to check the client. We just want to
8537 	 * offline the PHCI
8538 	 */
8539 	phci_only = 1;
8540 	if (MDI_PHCI(dip))
8541 		mdi_phci_retire_finalize(dip, phci_only);
8542 }
8543