xref: /illumos-gate/usr/src/uts/common/os/instance.c (revision a7cee4e9766ebda975dd156d1f10a70f51c242f0)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2026 Oxide Computer Company
24  */
25 
26 /*
27  * Instance number assignment code
28  */
29 
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/errno.h>
33 #include <sys/systm.h>
34 #include <sys/kobj.h>
35 #include <sys/t_lock.h>
36 #include <sys/kmem.h>
37 #include <sys/cmn_err.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/autoconf.h>
41 #include <sys/systeminfo.h>
42 #include <sys/hwconf.h>
43 #include <sys/reboot.h>
44 #include <sys/ddi_impldefs.h>
45 #include <sys/instance.h>
46 #include <sys/debug.h>
47 #include <sys/sysevent.h>
48 #include <sys/modctl.h>
49 #include <sys/console.h>
50 #include <sys/cladm.h>
51 #include <sys/sysmacros.h>
52 #include <sys/crc32.h>
53 
54 
55 static void in_preassign_instance(void);
56 static void i_log_devfs_instance_mod(void);
57 static int in_get_infile(char *);
58 static void in_removenode(struct devnames *dnp, in_node_t *mp, in_node_t *ap);
59 static in_node_t *in_alloc_node(char *name, char *addr);
60 static int in_eqstr(char *a, char *b);
61 static char *in_name_addr(char **cpp, char **addrp);
62 static in_node_t *in_devwalk(dev_info_t *dip, in_node_t **ap, char *addr);
63 static in_node_t *in_devwalk_create(dev_info_t *dip);
64 static void in_dealloc_node(in_node_t *np);
65 static in_node_t *in_make_path(char *path);
66 static void in_enlist(in_node_t *ap, in_node_t *np);
67 static int in_inuse(int instance, char *name);
68 static void in_hashdrv(in_drv_t *dp);
69 static in_drv_t *in_drvwalk(in_node_t *np, char *binding_name);
70 static in_drv_t *in_alloc_drv(char *bindingname);
71 static void in_endrv(in_node_t *np, in_drv_t *dp);
72 static void in_dq_drv(in_drv_t *np);
73 static void in_removedrv(struct devnames *dnp, in_drv_t *mp);
74 static int in_pathin(char *cp, int instance, char *bname, struct bind **args);
75 static int in_next_instance_block(major_t, int);
76 static int in_next_instance(major_t);
77 
78 #pragma weak plat_ioaliases_init
79 
80 
81 /* external functions */
82 extern char *i_binding_to_drv_name(char *bname);
83 extern void plat_ioaliases_init(void);
84 
85 /*
86  * This plus devnames defines the entire software state of the instance world.
87  */
88 typedef struct in_softstate {
89 	in_node_t	*ins_root;	/* the root of our instance tree */
90 	in_drv_t	*ins_no_major;	/* majorless drv entries */
91 	/*
92 	 * Used to serialize access to data structures
93 	 */
94 	void		*ins_thread;
95 	kmutex_t	ins_serial;
96 	kcondvar_t	ins_serial_cv;
97 	int		ins_busy;
98 	boolean_t	ins_dirty;	/* instance info needs flush */
99 } in_softstate_t;
100 
101 static in_softstate_t e_ddi_inst_state;
102 
103 /*
104  * State transition information:
105  * e_ddi_inst_state contains, among other things, the root of a tree of
106  * device nodes used to track instance number assignments.
107  * Each device node may contain multiple driver bindings, represented
108  * by a linked list of in_drv_t nodes, each with an instance assignment
109  * (except for root node). Each in_drv node can be in one of 3 states,
110  * indicated by ind_state:
111  *
112  * IN_UNKNOWN:	Each node created in this state.  The instance number of
113  *	this node is not known.  ind_instance is set to -1.
114  * IN_PROVISIONAL:  When a node is assigned an instance number in
115  *	e_ddi_assign_instance(), its state is set to IN_PROVISIONAL.
116  *	Subsequently, the framework will always call either
117  *	e_ddi_keep_instance() which makes the node IN_PERMANENT
118  *	or e_ddi_free_instance(), which deletes the node.
119  * IN_PERMANENT:
120  *	If e_ddi_keep_instance() is called on an IN_PROVISIONAL node,
121  *	its state is set to IN_PERMANENT.
122  */
123 
124 static char *instance_file = INSTANCE_FILE;
125 static char *instance_file_backup = INSTANCE_FILE INSTANCE_FILE_SUFFIX;
126 
127 /*
128  * Return values for in_get_infile().
129  */
130 #define	PTI_FOUND	0
131 #define	PTI_NOT_FOUND	1
132 #define	PTI_REBUILD	2
133 
134 int	instance_searchme = 0;	/* testing: use complex code path */
135 
136 /*
137  * Path to instance file magic string used for first time boot after
138  * an install.  If this is the first string in the file we will
139  * automatically rebuild the file.
140  */
141 #define	PTI_MAGIC_STR		"#path_to_inst_bootstrap_1"
142 #define	PTI_MAGIC_STR_LEN	(sizeof (PTI_MAGIC_STR) - 1)
143 
144 void
145 e_ddi_instance_init(void)
146 {
147 	char *file;
148 	int rebuild = 1;
149 	struct in_drv *dp;
150 
151 	mutex_init(&e_ddi_inst_state.ins_serial, NULL, MUTEX_DEFAULT, NULL);
152 	cv_init(&e_ddi_inst_state.ins_serial_cv, NULL, CV_DEFAULT, NULL);
153 
154 	/*
155 	 * Only one thread is allowed to change the state of the instance
156 	 * number assignments on the system at any given time.
157 	 * Note that this is not really necessary, as we are single-threaded
158 	 * here, but it won't hurt, and it allows us to keep ASSERTS for
159 	 * our assumptions in the code.
160 	 */
161 	e_ddi_enter_instance();
162 
163 	/*
164 	 * Init the ioaliases if the platform supports it
165 	 */
166 	if (&plat_ioaliases_init)
167 		plat_ioaliases_init();
168 
169 	/*
170 	 * Create the root node, instance zallocs to 0.
171 	 * The name and address of this node never get examined, we always
172 	 * start searching with its first child.
173 	 */
174 	ASSERT(e_ddi_inst_state.ins_root == NULL);
175 	e_ddi_inst_state.ins_root = in_alloc_node(NULL, NULL);
176 	dp = in_alloc_drv("rootnex");
177 	in_endrv(e_ddi_inst_state.ins_root, dp);
178 
179 	file = instance_file;
180 	switch (in_get_infile(file)) {
181 	default:
182 	case PTI_NOT_FOUND:
183 		/* make sure path_to_inst is recreated */
184 		boothowto |= RB_RECONFIG;
185 
186 		/*
187 		 * Something is wrong. First try the backup file.
188 		 * If not found, rebuild path_to_inst. Emit a
189 		 * message about the problem.
190 		 */
191 		cmn_err(CE_WARN, "%s empty or not found", file);
192 
193 		file = instance_file_backup;
194 		if (in_get_infile(file) != PTI_FOUND) {
195 			cmn_err(CE_NOTE, "rebuilding device instance data");
196 			break;
197 		}
198 		cmn_err(CE_NOTE, "using backup instance data in %s", file);
199 		/*FALLTHROUGH*/
200 
201 	case PTI_FOUND:
202 		/*
203 		 * We've got a readable file
204 		 * parse the file into the instance tree
205 		 */
206 		(void) read_binding_file(file, NULL, in_pathin);
207 		rebuild = 0;
208 		break;
209 
210 	case PTI_REBUILD:
211 		/*
212 		 * path_to_inst has magic str requesting a create
213 		 * Convert boot to reconfig boot to ensure /dev is
214 		 * in sync with new path_to_inst.
215 		 */
216 		boothowto |= RB_RECONFIG;
217 		cmn_err(CE_CONT,
218 		    "?Using default device instance data\n");
219 		break;
220 	}
221 
222 	/*
223 	 * The OBP device tree has been copied to the kernel and
224 	 * bound to drivers at this point. We walk the per-driver
225 	 * list to preassign instances. Since the bus addr is
226 	 * unknown at this point, we cannot place the instance
227 	 * number in the instance tree. This will be done at
228 	 * a later time.
229 	 */
230 	if (rebuild)
231 		in_preassign_instance();
232 
233 	e_ddi_exit_instance();
234 }
235 
236 static void
237 in_preassign_instance()
238 {
239 	major_t		m;
240 	struct devnames	*dnp;
241 	dev_info_t	*dip;
242 	extern major_t	devcnt;
243 
244 	for (m = 0; m < devcnt; m++) {
245 		dnp = &devnamesp[m];
246 		dip = dnp->dn_head;
247 		while (dip) {
248 			DEVI(dip)->devi_instance = dnp->dn_instance;
249 			dnp->dn_instance++;
250 			dip = ddi_get_next(dip);
251 		}
252 
253 		/*
254 		 * The preassign instance numbers are not fully
255 		 * accounted for until e_ddi_assign_instance().
256 		 * We can't fully account for them now because we
257 		 * don't currently have a unit-address. Because of
258 		 * this, we need to remember the preassign boundary
259 		 * to avoid ordering issues related to
260 		 * e_ddi_assign_instance of a preassigned value .vs.
261 		 * re-assignment of the same value for a dynamic
262 		 * SID node created by bus_config.
263 		 */
264 		dnp->dn_pinstance = dnp->dn_instance;
265 		dnp->dn_instance = IN_SEARCHME;
266 	}
267 }
268 
269 /*
270  * Checks to see if the /etc/path_to_inst file exists and whether or not
271  * it has the magic string in it.
272  *
273  * Returns one of the following:
274  *
275  *	PTI_FOUND	- We have found the /etc/path_to_inst file
276  *	PTI_REBUILD	- We have found the /etc/path_to_inst file and the
277  *			  first line was PTI_MAGIC_STR.
278  *	PTI_NOT_FOUND	- We did not find the /etc/path_to_inst file
279  *
280  */
281 static int
282 in_get_infile(char *filename)
283 {
284 	struct _buf *file;
285 	int return_val;
286 	char buf[PTI_MAGIC_STR_LEN];
287 
288 	/*
289 	 * Try to open the file.
290 	 */
291 	if ((file = kobj_open_file(filename)) == (struct _buf *)-1) {
292 		return (PTI_NOT_FOUND);
293 	}
294 	return_val = PTI_FOUND;
295 
296 	/*
297 	 * Read the first PTI_MAGIC_STR_LEN bytes from the file to see if
298 	 * it contains the magic string.  If there aren't that many bytes
299 	 * in the file, then assume file is correct and no magic string
300 	 * and move on.
301 	 */
302 	switch (kobj_read_file(file, buf, PTI_MAGIC_STR_LEN, 0)) {
303 
304 	case PTI_MAGIC_STR_LEN:
305 		/*
306 		 * If the first PTI_MAGIC_STR_LEN bytes are the magic string
307 		 * then return PTI_REBUILD.
308 		 */
309 		if (strncmp(PTI_MAGIC_STR, buf, PTI_MAGIC_STR_LEN) == 0)
310 			return_val = PTI_REBUILD;
311 		break;
312 
313 	case 0:
314 		/*
315 		 * If the file is zero bytes in length, then consider the
316 		 * file to not be found
317 		 */
318 		return_val = PTI_NOT_FOUND;
319 
320 	default: /* Do nothing we have a good file */
321 		break;
322 	}
323 
324 	kobj_close_file(file);
325 	return (return_val);
326 }
327 
328 int
329 is_pseudo_device(dev_info_t *dip)
330 {
331 	dev_info_t	*pdip;
332 
333 	for (pdip = ddi_get_parent(dip); pdip && pdip != ddi_root_node();
334 	    pdip = ddi_get_parent(pdip)) {
335 		if (strcmp(ddi_get_name(pdip), DEVI_PSEUDO_NEXNAME) == 0)
336 			return (1);
337 	}
338 	return (0);
339 }
340 
341 
342 static void
343 in_set_instance(dev_info_t *dip, in_drv_t *dp, major_t major)
344 {
345 	/* use preassigned instance if available */
346 	if (DEVI(dip)->devi_instance != -1)
347 		dp->ind_instance = DEVI(dip)->devi_instance;
348 	else
349 		dp->ind_instance = in_next_instance(major);
350 }
351 
352 /*
353  * Return 1 if instance block was assigned for the path.
354  *
355  * For multi-port NIC cards, sequential instance assignment across all
356  * ports on a card is highly desirable since the ppa is typically the
357  * same as the instance number, and the ppa is used in the NIC's public
358  * /dev name. This sequential assignment typically occurs as a result
359  * of in_preassign_instance() after initial install, or by
360  * i_ndi_init_hw_children() for NIC ports that share a common parent.
361  *
362  * Some NIC cards however use multi-function bridge chips, and to
363  * support sequential instance assignment accross all ports, without
364  * disabling multi-threaded attach, we have a (currently) undocumented
365  * hack to allocate instance numbers in contiguous blocks based on
366  * driver.conf properties.
367  *
368  *                       ^
369  *           /----------   ------------\
370  *        pci@0                      pci@0,1	MULTI-FUNCTION BRIDGE CHIP
371  *       /     \                    /       \
372  * FJSV,e4ta@4  FJSV,e4ta@4,1   FJSV,e4ta@6 FJSV,e4ta@6,1	NIC PORTS
373  *      n            n+2             n+2         n+3		INSTANCE
374  *
375  * For the above example, the following driver.conf properties would be
376  * used to guarantee sequential instance number assignment.
377  *
378  * ddi-instance-blocks ="ib-FJSVe4ca", "ib-FJSVe4ta", "ib-generic";
379  * ib-FJSVe4ca =	"/pci@0/FJSV,e4ca@4", "/pci@0/FJSV,e4ca@4,1",
380  *			"/pci@0,1/FJSV,e4ca@6", "/pci@0,1/FJSV,e4ca@6,1";
381  * ib-FJSVe4ta =	"/pci@0/FJSV,e4ta@4", "/pci@0/FJSV,e4ta@4,1",
382  *			"/pci@0,1/FJSV,e4ta@6", "/pci@0,1/FJSV,e4ta@6,1";
383  * ib-generic =		"/pci@0/network@4", "/pci@0/network@4,1",
384  *			"/pci@0,1/network@6", "/pci@0,1/network@6,1";
385  *
386  * The value of the 'ddi-instance-blocks' property references a series
387  * of card specific properties, like 'ib-FJSV-e4ta', who's value
388  * defines a single 'instance block'.  The 'instance block' describes
389  * all the paths below a multi-function bridge, where each path is
390  * called an 'instance path'.  The 'instance block' property value is a
391  * series of 'instance paths'.  The number of 'instance paths' in an
392  * 'instance block' defines the size of the instance block, and the
393  * ordering of the 'instance paths' defines the instance number
394  * assignment order for paths going through the 'instance block'.
395  *
396  * In the instance assignment code below, if a (path, driver) that
397  * currently has no instance number has a path that goes through an
398  * 'instance block', then block instance number allocation occurs.  The
399  * block allocation code will find a sequential set of unused instance
400  * numbers, and assign instance numbers for all the paths in the
401  * 'instance block'.  Each path is assigned a persistent instance
402  * number, even paths that don't exist in the device tree or fail
403  * probe(9E).
404  */
405 static int
406 in_assign_instance_block(dev_info_t *dip)
407 {
408 	char		**ibn;		/* instance block names */
409 	uint_t		nibn;		/* number of instance block names */
410 	uint_t		ibni;		/* ibn index */
411 	char		*driver;
412 	major_t		major;
413 	char		*path;
414 	char		*addr;
415 	int		plen;
416 	char		**ibp;		/* instance block paths */
417 	uint_t		nibp;		/* number of paths in instance block */
418 	uint_t		ibpi;		/* ibp index */
419 	int		ibplen;		/* length of instance block path */
420 	char		*ipath;
421 	int		instance_base;
422 	int		splice;
423 	int		i;
424 
425 	/* check for fresh install case (in miniroot) */
426 	if (DEVI(dip)->devi_instance != -1)
427 		return (0);			/* already assigned */
428 
429 	/*
430 	 * Check to see if we need to allocate a block of contiguous instance
431 	 * numbers by looking for the 'ddi-instance-blocks' property.
432 	 */
433 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
434 	    "ddi-instance-blocks", &ibn, &nibn) != DDI_SUCCESS)
435 		return (0);			/* no instance block needed */
436 
437 	/*
438 	 * Get information out about node we are processing.
439 	 *
440 	 * NOTE: Since the node is not yet at DS_INITIALIZED, ddi_pathname()
441 	 * will not return the unit-address of the final path component even
442 	 * though the node has an established devi_addr unit-address - so we
443 	 * need to add the unit-address by hand.
444 	 */
445 	driver = (char *)ddi_driver_name(dip);
446 	major = ddi_driver_major(dip);
447 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
448 	(void) ddi_pathname(dip, path);
449 	if ((addr =  ddi_get_name_addr(dip)) != NULL) {
450 		(void) strcat(path, "@");
451 		(void) strcat(path, addr);
452 	}
453 	plen = strlen(path);
454 
455 	/* loop through instance block names */
456 	for (ibni = 0; ibni < nibn; ibni++) {
457 		if (ibn[ibni] == NULL)
458 			continue;
459 
460 		/* lookup instance block */
461 		if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, dip,
462 		    DDI_PROP_DONTPASS, ibn[ibni],
463 		    &ibp, &nibp) != DDI_SUCCESS) {
464 			cmn_err(CE_WARN,
465 			    "no devinition for instance block '%s' in %s.conf",
466 			    ibn[ibni], driver);
467 			continue;
468 		}
469 
470 		/* Does 'path' go through this instance block? */
471 		for (ibpi = 0; ibpi < nibp; ibpi++) {
472 			if (ibp[ibpi] == NULL)
473 				continue;
474 			ibplen = strlen(ibp[ibpi]);
475 			if ((ibplen <= plen) &&
476 			    (strcmp(ibp[ibpi], path + plen - ibplen) == 0))
477 				break;
478 
479 		}
480 		if (ibpi >= nibp) {
481 			ddi_prop_free(ibp);
482 			continue;		/* no try next instance block */
483 		}
484 
485 		/* yes, allocate and assign instances for all paths in block */
486 
487 		/*
488 		 * determine where we splice in instance paths and verify
489 		 * that none of the paths are too long.
490 		 */
491 		splice = plen - ibplen;
492 		for (i = 0; i < nibp; i++) {
493 			if ((splice + strlen(ibp[i])+ 1) >= MAXPATHLEN) {
494 				cmn_err(CE_WARN,
495 				    "path %d through instance block '%s' from "
496 				    "%s.conf too long", i, ibn[ibni], driver);
497 				break;
498 			}
499 		}
500 		if (i < nibp) {
501 			ddi_prop_free(ibp);
502 			continue;		/* too long */
503 		}
504 
505 		/* allocate the instance block - no more failures */
506 		instance_base = in_next_instance_block(major, nibp);
507 
508 		ipath = kmem_alloc(MAXPATHLEN, KM_SLEEP);
509 		for (ibpi = 0; ibpi < nibp; ibpi++) {
510 			if (ibp[ibpi] == NULL)
511 				continue;
512 			(void) strcpy(ipath, path);
513 			(void) strcpy(ipath + splice, ibp[ibpi]);
514 			(void) in_pathin(ipath,
515 			    instance_base + ibpi, driver, NULL);
516 		}
517 
518 		/* free allocations */
519 		kmem_free(ipath, MAXPATHLEN);
520 		ddi_prop_free(ibp);
521 		kmem_free(path, MAXPATHLEN);
522 		ddi_prop_free(ibn);
523 
524 		/* notify devfsadmd to sync of path_to_inst file */
525 		mutex_enter(&e_ddi_inst_state.ins_serial);
526 		i_log_devfs_instance_mod();
527 		e_ddi_inst_state.ins_dirty = B_TRUE;
528 		mutex_exit(&e_ddi_inst_state.ins_serial);
529 		return (1);
530 	}
531 
532 	/* our path did not go through any of of the instance blocks */
533 	kmem_free(path, MAXPATHLEN);
534 	ddi_prop_free(ibn);
535 	return (0);
536 }
537 
538 /*
539  * Look up an instance number for a dev_info node, and assign one if it does
540  * not have one (the dev_info node has devi_name and devi_addr already set).
541  */
542 uint_t
543 e_ddi_assign_instance(dev_info_t *dip)
544 {
545 	in_node_t *ap, *np;
546 	in_drv_t *dp;
547 	major_t major;
548 	uint_t ret;
549 	char *bname;
550 
551 	/*
552 	 * Allow implementation to override
553 	 */
554 	if ((ret = impl_assign_instance(dip)) != (uint_t)-1)
555 		return (ret);
556 
557 	/*
558 	 * If this is a pseudo-device to which the pseudo nexus driver
559 	 * assigned an instance number (as happens for nodes enumerated from
560 	 * driver.conf files) use that instance. A pseudo child that was
561 	 * created without an instance, such as a node enumerated by a pseudo
562 	 * nexus driver itself, falls through and is assigned an instance from
563 	 * the instance tree like any other device.
564 	 */
565 	if (is_pseudo_device(dip)) {
566 		int instance = ddi_get_instance(dip);
567 
568 		if (instance != -1)
569 			return (instance);
570 	}
571 
572 	/*
573 	 * Only one thread is allowed to change the state of the instance
574 	 * number assignments on the system at any given time.
575 	 */
576 	e_ddi_enter_instance();
577 
578 	/*
579 	 * Look for instance node, allocate one if not found
580 	 */
581 	np = in_devwalk(dip, &ap, NULL);
582 	if (np == NULL) {
583 		if (in_assign_instance_block(dip)) {
584 			np = in_devwalk(dip, &ap, NULL);
585 		} else {
586 			np = in_devwalk_create(dip);
587 			ASSERT(np != NULL);
588 		}
589 	}
590 	ASSERT(np == in_devwalk(dip, &ap, NULL));
591 
592 	/*
593 	 * Link the devinfo node and in_node_t
594 	 */
595 	if (DEVI(dip)->devi_in_node || np->in_devi) {
596 		ddi_err(DER_MODE, dip, "devinfo and  instance node (%p) "
597 		    "interlink fields are not NULL", (void *)np);
598 	}
599 	DEVI(dip)->devi_in_node = np;
600 	np->in_devi = dip;
601 
602 	/*
603 	 * Look for driver entry, allocate one if not found
604 	 */
605 	bname = (char *)ddi_driver_name(dip);
606 	dp = in_drvwalk(np, bname);
607 	if (dp == NULL) {
608 
609 		if (ddi_aliases_present == B_TRUE) {
610 			e_ddi_borrow_instance(dip, np);
611 		}
612 
613 		if ((dp = in_drvwalk(np, bname)) == NULL) {
614 			dp = in_alloc_drv(bname);
615 			ASSERT(dp != NULL);
616 			major = ddi_driver_major(dip);
617 			ASSERT(major != DDI_MAJOR_T_NONE);
618 			in_endrv(np, dp);
619 			in_set_instance(dip, dp, major);
620 			dp->ind_state = IN_PROVISIONAL;
621 			in_hashdrv(dp);
622 		} else {
623 			dp->ind_state = IN_BORROWED;
624 		}
625 	}
626 
627 	ret = dp->ind_instance;
628 
629 	e_ddi_exit_instance();
630 	return (ret);
631 }
632 
633 static int
634 mkpathname(char *path, in_node_t *np, int len)
635 {
636 	int len_needed;
637 
638 	if (np == e_ddi_inst_state.ins_root)
639 		return (DDI_SUCCESS);
640 
641 	if (mkpathname(path, np->in_parent, len) == DDI_FAILURE)
642 		return (DDI_FAILURE);
643 
644 	len_needed = strlen(path);
645 	len_needed += strlen(np->in_node_name) + 1;	/* for '/' */
646 	if (np->in_unit_addr) {
647 		len_needed += strlen(np->in_unit_addr) + 1;  /* for '@' */
648 	}
649 	len_needed += 1; /* for '\0' */
650 
651 	/*
652 	 * XX complain
653 	 */
654 	if (len_needed > len)
655 		return (DDI_FAILURE);
656 
657 	if (np->in_unit_addr[0] == '\0')
658 		(void) sprintf(path+strlen(path), "/%s", np->in_node_name);
659 	else
660 		(void) sprintf(path+strlen(path), "/%s@%s", np->in_node_name,
661 		    np->in_unit_addr);
662 
663 	return (DDI_SUCCESS);
664 }
665 
666 /*
667  * produce the path to the given instance of a major number.
668  * path must hold MAXPATHLEN string
669  */
670 int
671 e_ddi_instance_majorinstance_to_path(major_t major, uint_t inst, char *path)
672 {
673 	struct devnames	*dnp;
674 	in_drv_t	*dp;
675 	int		ret;
676 
677 	e_ddi_enter_instance();
678 
679 	/* look for the instance threaded off major */
680 	dnp = &devnamesp[major];
681 	for (dp = dnp->dn_inlist; dp != NULL; dp = dp->ind_next)
682 		if (dp->ind_instance == inst)
683 			break;
684 
685 	/* produce path from the node that uses the instance */
686 	if (dp) {
687 		*path = 0;
688 		ret = mkpathname(path, dp->ind_node, MAXPATHLEN);
689 	} else
690 		ret = DDI_FAILURE;
691 
692 	e_ddi_exit_instance();
693 	return (ret);
694 }
695 
696 /*
697  * Allocate a sequential block of instance numbers for the specified driver,
698  * and return the base instance number of the block.  The implementation
699  * depends on the list being sorted in ascending instance number sequence.
700  * When there are no 'holes' in the allocation sequence, dn_instance is the
701  * next available instance number. When dn_instance is IN_SEARCHME, hole(s)
702  * exists and a slower code path executes which tries to fill holes.
703  *
704  * The block returned can't be in the preassigned range.
705  */
706 static int
707 in_next_instance_block(major_t major, int block_size)
708 {
709 	int		prev;
710 	struct devnames	*dnp;
711 	in_drv_t	*dp;
712 	int		base;
713 	int		hole;
714 
715 	dnp = &devnamesp[major];
716 	ASSERT(major != DDI_MAJOR_T_NONE);
717 	ASSERT(e_ddi_inst_state.ins_busy);
718 	ASSERT(block_size);
719 
720 	/* check to see if we can do a quick allocation */
721 	if (!instance_searchme && (dnp->dn_instance != IN_SEARCHME)) {
722 		base = dnp->dn_instance;
723 		dnp->dn_instance += block_size;
724 		return (base);
725 	}
726 
727 	/*
728 	 * Use more complex code path, start by skipping preassign entries.
729 	 */
730 	for (dp = dnp->dn_inlist; dp; dp = dp->ind_next)
731 		if (dp->ind_instance >= dnp->dn_pinstance)
732 			break;		/* beyond preassign */
733 
734 	/* No non-preassign entries, allocate block at preassign base. */
735 	if (dp == NULL) {
736 		base = dnp->dn_pinstance;
737 		if (base == 0)
738 			dnp->dn_instance = block_size;
739 		return (base);
740 	}
741 
742 	/* See if we fit in hole at beginning (after preassigns) */
743 	prev = dp->ind_instance;
744 	if ((prev - dnp->dn_pinstance) >= block_size)
745 		return (dnp->dn_pinstance);	/* we fit in beginning hole */
746 
747 	/* search the list for a large enough hole */
748 	for (dp = dp->ind_next, hole = 0; dp; dp = dp->ind_next) {
749 		if (dp->ind_instance != (prev + 1))
750 			hole++;			/* we have a hole */
751 		if (dp->ind_instance >= (prev + block_size + 1))
752 			break;			/* we fit in hole */
753 		prev = dp->ind_instance;
754 	}
755 
756 	/*
757 	 * If hole is zero then all holes are patched and we can resume
758 	 * quick allocations, but don't resume quick allocation if there is
759 	 * a preassign.
760 	 */
761 	if ((hole == 0) && (dnp->dn_pinstance == 0))
762 		dnp->dn_instance = prev + 1 + block_size;
763 
764 	return (prev + 1);
765 }
766 
767 /* assign instance block of size 1 */
768 static int
769 in_next_instance(major_t major)
770 {
771 	return (in_next_instance_block(major, 1));
772 }
773 
774 /*
775  * This call causes us to *forget* the instance number we've generated
776  * for a given device if it was not permanent.
777  */
778 void
779 e_ddi_free_instance(dev_info_t *dip, char *addr)
780 {
781 	char *name;
782 	in_node_t *np;
783 	in_node_t *ap;	/* ancestor node */
784 	major_t major;
785 	struct devnames *dnp;
786 	in_drv_t *dp;	/* in_drv entry */
787 
788 	/*
789 	 * Allow implementation override
790 	 */
791 	if (impl_free_instance(dip) == DDI_SUCCESS)
792 		return;
793 
794 	/*
795 	 * A pseudo-device that was never entered into the instance tree,
796 	 * because the pseudo nexus preassigned its instance, has nothing
797 	 * to free.
798 	 */
799 	if (is_pseudo_device(dip) && DEVI(dip)->devi_in_node == NULL) {
800 		return;
801 	}
802 
803 	name = (char *)ddi_driver_name(dip);
804 	major = ddi_driver_major(dip);
805 	ASSERT(major != DDI_MAJOR_T_NONE);
806 	dnp = &devnamesp[major];
807 	/*
808 	 * Only one thread is allowed to change the state of the instance
809 	 * number assignments on the system at any given time.
810 	 */
811 	e_ddi_enter_instance();
812 	np = in_devwalk(dip, &ap, addr);
813 	ASSERT(np);
814 
815 	/*
816 	 * Break the interlink between dip and np
817 	 */
818 	if (DEVI(dip)->devi_in_node != np || np->in_devi != dip) {
819 		ddi_err(DER_MODE, dip, "devinfo node linked to "
820 		    "wrong instance node: %p", (void *)np);
821 	}
822 	DEVI(dip)->devi_in_node = NULL;
823 	np->in_devi = NULL;
824 
825 	dp = in_drvwalk(np, name);
826 	ASSERT(dp);
827 	if (dp->ind_state == IN_PROVISIONAL) {
828 		in_removedrv(dnp, dp);
829 	} else if (dp->ind_state == IN_BORROWED) {
830 		dp->ind_state = IN_PERMANENT;
831 		e_ddi_return_instance(dip, addr, np);
832 	}
833 	if (np->in_drivers == NULL) {
834 		in_removenode(dnp, np, ap);
835 	}
836 	e_ddi_exit_instance();
837 }
838 
839 /*
840  * This makes our memory of an instance assignment permanent
841  */
842 void
843 e_ddi_keep_instance(dev_info_t *dip)
844 {
845 	in_node_t *np, *ap;
846 	in_drv_t *dp;
847 
848 	/* Don't make nulldriver instance assignments permanent */
849 	if (ddi_driver_major(dip) == nulldriver_major)
850 		return;
851 
852 	/*
853 	 * Allow implementation override
854 	 */
855 	if (impl_keep_instance(dip) == DDI_SUCCESS)
856 		return;
857 
858 	/*
859 	 * Nothing to do for a pseudo device that was never entered into
860 	 * the instance tree.
861 	 */
862 	if (is_pseudo_device(dip) && DEVI(dip)->devi_in_node == NULL)
863 		return;
864 
865 	/*
866 	 * Only one thread is allowed to change the state of the instance
867 	 * number assignments on the system at any given time.
868 	 */
869 	e_ddi_enter_instance();
870 	np = in_devwalk(dip, &ap, NULL);
871 	ASSERT(np);
872 	dp = in_drvwalk(np, (char *)ddi_driver_name(dip));
873 	ASSERT(dp);
874 
875 	mutex_enter(&e_ddi_inst_state.ins_serial);
876 	if (dp->ind_state == IN_PROVISIONAL || dp->ind_state == IN_BORROWED) {
877 		dp->ind_state = IN_PERMANENT;
878 		i_log_devfs_instance_mod();
879 		e_ddi_inst_state.ins_dirty = B_TRUE;
880 	}
881 	mutex_exit(&e_ddi_inst_state.ins_serial);
882 	e_ddi_exit_instance();
883 }
884 
885 /*
886  * A new major has been added to the system.  Run through the orphan list
887  * and try to attach each one to a driver's list.
888  */
889 void
890 e_ddi_unorphan_instance_nos()
891 {
892 	in_drv_t *dp, *ndp;
893 
894 	/*
895 	 * disconnect the orphan list, and call in_hashdrv for each item
896 	 * on it
897 	 */
898 
899 	/*
900 	 * Only one thread is allowed to change the state of the instance
901 	 * number assignments on the system at any given time.
902 	 */
903 	e_ddi_enter_instance();
904 	if (e_ddi_inst_state.ins_no_major == NULL) {
905 		e_ddi_exit_instance();
906 		return;
907 	}
908 	/*
909 	 * Hash instance list to devnames structure of major.
910 	 * Note that if there is not a valid major number for the
911 	 * node, in_hashdrv will put it back on the no_major list.
912 	 */
913 	dp = e_ddi_inst_state.ins_no_major;
914 	e_ddi_inst_state.ins_no_major = NULL;
915 	while (dp) {
916 		ndp = dp->ind_next;
917 		ASSERT(dp->ind_state != IN_UNKNOWN);
918 		dp->ind_next = NULL;
919 		in_hashdrv(dp);
920 		dp = ndp;
921 	}
922 	e_ddi_exit_instance();
923 }
924 
925 static void
926 in_removenode(struct devnames *dnp, in_node_t *mp, in_node_t *ap)
927 {
928 	in_node_t *np;
929 
930 	ASSERT(e_ddi_inst_state.ins_busy);
931 
932 	/*
933 	 * Assertion: parents are always instantiated by the framework
934 	 * before their children, destroyed after them
935 	 */
936 	ASSERT(mp->in_child == NULL);
937 	/*
938 	 * Assertion: drv entries are always removed before their owning nodes
939 	 */
940 	ASSERT(mp->in_drivers == NULL);
941 	/*
942 	 * Take the node out of the tree
943 	 */
944 	if (ap->in_child == mp) {
945 		ap->in_child = mp->in_sibling;
946 		in_dealloc_node(mp);
947 		return;
948 	} else {
949 		for (np = ap->in_child; np; np = np->in_sibling) {
950 			if (np->in_sibling == mp) {
951 				np->in_sibling = mp->in_sibling;
952 				in_dealloc_node(mp);
953 				return;
954 			}
955 		}
956 	}
957 	panic("in_removenode dnp %p mp %p", (void *)dnp, (void *)mp);
958 }
959 
960 /*
961  * Recursive ascent
962  *
963  * This now only does half the job.  It finds the node, then the caller
964  * has to search the node for the binding name
965  */
966 static in_node_t *
967 in_devwalk(dev_info_t *dip, in_node_t **ap, char *addr)
968 {
969 	in_node_t *np;
970 	char *name;
971 
972 	ASSERT(dip);
973 	ASSERT(e_ddi_inst_state.ins_busy);
974 	if (dip == ddi_root_node()) {
975 		*ap = NULL;
976 		return (e_ddi_inst_state.ins_root);
977 	}
978 	/*
979 	 * call up to find parent, then look through the list of kids
980 	 * for a match
981 	 */
982 	np = in_devwalk(ddi_get_parent(dip), ap, NULL);
983 	if (np == NULL)
984 		return (np);
985 	*ap = np;
986 	np = np->in_child;
987 	name = ddi_node_name(dip);
988 	if (addr == NULL)
989 		addr = ddi_get_name_addr(dip);
990 
991 	while (np) {
992 		if (in_eqstr(np->in_node_name, name) &&
993 		    in_eqstr(np->in_unit_addr, addr)) {
994 			return (np);
995 		}
996 		np = np->in_sibling;
997 	}
998 
999 	return (np);
1000 }
1001 
1002 /*
1003  * As in_devwalk(), but create any nodes that are missing from the tree
1004  * along the way. A node whose ancestors were never entered into the tree,
1005  * such as a child enumerated by a pseudo nexus driver whose own instance
1006  * was preassigned from driver.conf, still takes its proper place in the
1007  * tree this way. Intermediate nodes created here carry no driver entries,
1008  * as with the intermediate path components created by in_pathin().
1009  */
1010 static in_node_t *
1011 in_devwalk_create(dev_info_t *dip)
1012 {
1013 	in_node_t *pnp, *np;
1014 	char *name, *addr;
1015 
1016 	ASSERT(dip);
1017 	ASSERT(e_ddi_inst_state.ins_busy);
1018 	if (dip == ddi_root_node())
1019 		return (e_ddi_inst_state.ins_root);
1020 
1021 	pnp = in_devwalk_create(ddi_get_parent(dip));
1022 	name = ddi_node_name(dip);
1023 	addr = ddi_get_name_addr(dip);
1024 
1025 	for (np = pnp->in_child; np != NULL; np = np->in_sibling) {
1026 		if (in_eqstr(np->in_node_name, name) &&
1027 		    in_eqstr(np->in_unit_addr, addr)) {
1028 			return (np);
1029 		}
1030 	}
1031 
1032 	np = in_alloc_node(name, addr);
1033 	ASSERT(np != NULL);
1034 	in_enlist(pnp, np);
1035 
1036 	return (np);
1037 }
1038 
1039 /*
1040  * Create a node specified by cp and assign it the given instance no.
1041  */
1042 static int
1043 in_pathin(char *cp, int instance, char *bname, struct bind **args)
1044 {
1045 	in_node_t *np;
1046 	in_drv_t *dp;
1047 	char *name;
1048 
1049 	ASSERT(e_ddi_inst_state.ins_busy);
1050 	ASSERT(args == NULL);
1051 
1052 	/*
1053 	 * Give a warning to the console.
1054 	 * return value ignored
1055 	 */
1056 	if (cp[0] != '/' || instance == -1 || bname == NULL) {
1057 		cmn_err(CE_WARN,
1058 		    "invalid instance file entry %s %d",
1059 		    cp, instance);
1060 		return (0);
1061 	}
1062 
1063 	if ((name  = i_binding_to_drv_name(bname)) != NULL)
1064 		bname = name;
1065 
1066 	np = in_make_path(cp);
1067 	ASSERT(np);
1068 
1069 	dp = in_drvwalk(np, bname);
1070 	if (dp != NULL) {
1071 		cmn_err(CE_WARN,
1072 		    "multiple instance number assignments for "
1073 		    "'%s' (driver %s), %d used",
1074 		    cp, bname, dp->ind_instance);
1075 		return (0);
1076 	}
1077 
1078 	if (in_inuse(instance, bname)) {
1079 		cmn_err(CE_WARN,
1080 		    "instance already in use: %s %d", cp, instance);
1081 		return (0);
1082 	}
1083 
1084 	dp = in_alloc_drv(bname);
1085 	in_endrv(np, dp);
1086 	dp->ind_instance = instance;
1087 	dp->ind_state = IN_PERMANENT;
1088 	in_hashdrv(dp);
1089 
1090 	return (0);
1091 }
1092 
1093 /*
1094  * Create (or find) the node named by path by recursively descending from the
1095  * root's first child (we ignore the root, which is never named)
1096  */
1097 static in_node_t *
1098 in_make_path(char *path)
1099 {
1100 	in_node_t *ap;		/* ancestor pointer */
1101 	in_node_t *np;		/* working node pointer */
1102 	in_node_t *rp;		/* return node pointer */
1103 	char buf[MAXPATHLEN];	/* copy of string so we can change it */
1104 	char *cp, *name, *addr;
1105 
1106 	ASSERT(e_ddi_inst_state.ins_busy);
1107 
1108 	if (path == NULL || path[0] != '/')
1109 		return (NULL);
1110 
1111 	(void) snprintf(buf, sizeof (buf), "%s", path);
1112 	cp = buf + 1;	/* skip over initial '/' in path */
1113 	name = in_name_addr(&cp, &addr);
1114 
1115 	/*
1116 	 * In S9 and earlier releases, the path_to_inst file
1117 	 * SunCluster was prepended with "/node@#". This was
1118 	 * removed in S10. We skip the prefix if the prefix
1119 	 * still exists in /etc/path_to_inst. It is needed for
1120 	 * various forms of Solaris upgrade to work properly
1121 	 * in the SunCluster environment.
1122 	 */
1123 	if ((cluster_bootflags & CLUSTER_CONFIGURED) &&
1124 	    (strcmp(name, "node") == 0))
1125 		name = in_name_addr(&cp, &addr);
1126 
1127 	ap = e_ddi_inst_state.ins_root;
1128 	np = e_ddi_inst_state.ins_root->in_child;
1129 	rp = np;
1130 	while (name) {
1131 		while (name && np) {
1132 			if (in_eqstr(name, np->in_node_name) &&
1133 			    in_eqstr(addr, np->in_unit_addr)) {
1134 				name = in_name_addr(&cp, &addr);
1135 				if (name == NULL)
1136 					return (np);
1137 				ap = np;
1138 				np = np->in_child;
1139 			} else {
1140 				np = np->in_sibling;
1141 			}
1142 		}
1143 		np = in_alloc_node(name, addr);
1144 		in_enlist(ap, np);	/* insert into tree */
1145 		rp = np;	/* value to return if we quit */
1146 		ap = np;	/* new parent */
1147 		np = NULL;	/* can have no children */
1148 		name = in_name_addr(&cp, &addr);
1149 	}
1150 
1151 	return (rp);
1152 }
1153 
1154 /*
1155  * Insert node np into the tree as one of ap's children.
1156  */
1157 static void
1158 in_enlist(in_node_t *ap, in_node_t *np)
1159 {
1160 	in_node_t *mp;
1161 	ASSERT(e_ddi_inst_state.ins_busy);
1162 	/*
1163 	 * Make this node some other node's child or child's sibling
1164 	 */
1165 	ASSERT(ap && np);
1166 	if (ap->in_child == NULL) {
1167 		ap->in_child = np;
1168 	} else {
1169 		for (mp = ap->in_child; mp; mp = mp->in_sibling)
1170 			if (mp->in_sibling == NULL) {
1171 				mp->in_sibling = np;
1172 				break;
1173 			}
1174 	}
1175 	np->in_parent = ap;
1176 }
1177 
1178 /*
1179  * Insert drv entry dp onto a node's driver list
1180  */
1181 static void
1182 in_endrv(in_node_t *np, in_drv_t *dp)
1183 {
1184 	in_drv_t *mp;
1185 	ASSERT(e_ddi_inst_state.ins_busy);
1186 	ASSERT(np && dp);
1187 	mp = np->in_drivers;
1188 	np->in_drivers = dp;
1189 	dp->ind_next_drv = mp;
1190 	dp->ind_node = np;
1191 }
1192 
1193 /*
1194  * Parse the next name out of the path, null terminate it and update cp.
1195  * caller has copied string so we can mess with it.
1196  * Upon return *cpp points to the next section to be parsed, *addrp points
1197  * to the current address substring (or NULL if none) and we return the
1198  * current name substring (or NULL if none).  name and address substrings
1199  * are null terminated in place.
1200  */
1201 
1202 static char *
1203 in_name_addr(char **cpp, char **addrp)
1204 {
1205 	char *namep;	/* return value holder */
1206 	char *ap;	/* pointer to '@' in string */
1207 	char *sp;	/* pointer to '/' in string */
1208 
1209 	if (*cpp == NULL || **cpp == '\0') {
1210 		*addrp = NULL;
1211 		return (NULL);
1212 	}
1213 	namep = *cpp;
1214 	sp = strchr(*cpp, '/');
1215 	if (sp != NULL) {	/* more to follow */
1216 		*sp = '\0';
1217 		*cpp = sp + 1;
1218 	} else {		/* this is last component. */
1219 		*cpp = NULL;
1220 	}
1221 	ap = strchr(namep, '@');
1222 	if (ap == NULL) {
1223 		*addrp = NULL;
1224 	} else {
1225 		*ap = '\0';		/* terminate the name */
1226 		*addrp = ap + 1;
1227 	}
1228 	return (namep);
1229 }
1230 
1231 /*
1232  * Allocate a node and storage for name and addr strings, and fill them in.
1233  */
1234 static in_node_t *
1235 in_alloc_node(char *name, char *addr)
1236 {
1237 	in_node_t *np;
1238 	char *cp;
1239 	size_t namelen;
1240 
1241 	ASSERT(e_ddi_inst_state.ins_busy);
1242 	/*
1243 	 * Has name or will become root
1244 	 */
1245 	ASSERT(name || e_ddi_inst_state.ins_root == NULL);
1246 	if (addr == NULL)
1247 		addr = "";
1248 	if (name == NULL)
1249 		namelen = 0;
1250 	else
1251 		namelen = strlen(name) + 1;
1252 	cp = kmem_zalloc(sizeof (in_node_t) + namelen + strlen(addr) + 1,
1253 	    KM_SLEEP);
1254 	np = (in_node_t *)cp;
1255 	if (name) {
1256 		np->in_node_name = cp + sizeof (in_node_t);
1257 		(void) strcpy(np->in_node_name, name);
1258 	}
1259 	np->in_unit_addr = cp + sizeof (in_node_t) + namelen;
1260 	(void) strcpy(np->in_unit_addr, addr);
1261 	return (np);
1262 }
1263 
1264 /*
1265  * Allocate a drv entry and storage for binding name string, and fill it in.
1266  */
1267 static in_drv_t *
1268 in_alloc_drv(char *bindingname)
1269 {
1270 	in_drv_t *dp;
1271 	char *cp;
1272 	size_t namelen;
1273 
1274 	ASSERT(e_ddi_inst_state.ins_busy);
1275 	/*
1276 	 * Has name or will become root
1277 	 */
1278 	ASSERT(bindingname || e_ddi_inst_state.ins_root == NULL);
1279 	if (bindingname == NULL)
1280 		namelen = 0;
1281 	else
1282 		namelen = strlen(bindingname) + 1;
1283 	cp = kmem_zalloc(sizeof (in_drv_t) + namelen, KM_SLEEP);
1284 	dp = (in_drv_t *)cp;
1285 	if (bindingname) {
1286 		dp->ind_driver_name = cp + sizeof (in_drv_t);
1287 		(void) strcpy(dp->ind_driver_name, bindingname);
1288 	}
1289 	dp->ind_state = IN_UNKNOWN;
1290 	dp->ind_instance = -1;
1291 	return (dp);
1292 }
1293 
1294 static void
1295 in_dealloc_node(in_node_t *np)
1296 {
1297 	/*
1298 	 * The root node can never be de-allocated
1299 	 */
1300 	ASSERT(np->in_node_name && np->in_unit_addr);
1301 	ASSERT(e_ddi_inst_state.ins_busy);
1302 	kmem_free(np, sizeof (in_node_t) + strlen(np->in_node_name)
1303 	    + strlen(np->in_unit_addr) + 2);
1304 }
1305 
1306 static void
1307 in_dealloc_drv(in_drv_t *dp)
1308 {
1309 	ASSERT(dp->ind_driver_name);
1310 	ASSERT(e_ddi_inst_state.ins_busy);
1311 	kmem_free(dp, sizeof (in_drv_t) + strlen(dp->ind_driver_name)
1312 	    + 1);
1313 }
1314 
1315 /*
1316  * Handle the various possible versions of "no address"
1317  */
1318 static int
1319 in_eqstr(char *a, char *b)
1320 {
1321 	if (a == b)	/* covers case where both are nulls */
1322 		return (1);
1323 	if (a == NULL && *b == 0)
1324 		return (1);
1325 	if (b == NULL && *a == 0)
1326 		return (1);
1327 	if (a == NULL || b == NULL)
1328 		return (0);
1329 	return (strcmp(a, b) == 0);
1330 }
1331 
1332 /*
1333  * Returns true if instance no. is already in use by named driver
1334  */
1335 static int
1336 in_inuse(int instance, char *name)
1337 {
1338 	major_t major;
1339 	in_drv_t *dp;
1340 	struct devnames *dnp;
1341 
1342 	ASSERT(e_ddi_inst_state.ins_busy);
1343 	/*
1344 	 * For now, if we've never heard of this device we assume it is not
1345 	 * in use, since we can't tell
1346 	 * XXX could do the weaker search through the nomajor list checking
1347 	 * XXX for the same name
1348 	 */
1349 	if ((major = ddi_name_to_major(name)) == DDI_MAJOR_T_NONE)
1350 		return (0);
1351 	dnp = &devnamesp[major];
1352 
1353 	dp = dnp->dn_inlist;
1354 	while (dp) {
1355 		if (dp->ind_instance == instance)
1356 			return (1);
1357 		dp = dp->ind_next;
1358 	}
1359 	return (0);
1360 }
1361 
1362 static void
1363 in_hashdrv(in_drv_t *dp)
1364 {
1365 	struct devnames *dnp;
1366 	in_drv_t *mp, *pp;
1367 	major_t major;
1368 
1369 	/* hash to no major list */
1370 	major = ddi_name_to_major(dp->ind_driver_name);
1371 	if (major == DDI_MAJOR_T_NONE) {
1372 		dp->ind_next = e_ddi_inst_state.ins_no_major;
1373 		e_ddi_inst_state.ins_no_major = dp;
1374 		return;
1375 	}
1376 
1377 	/*
1378 	 * dnp->dn_inlist is sorted by instance number.
1379 	 * Adding a new instance entry may introduce holes,
1380 	 * set dn_instance to IN_SEARCHME so the next instance
1381 	 * assignment may fill in holes.
1382 	 */
1383 	dnp = &devnamesp[major];
1384 	pp = mp = dnp->dn_inlist;
1385 	if (mp == NULL || dp->ind_instance < mp->ind_instance) {
1386 		/* prepend as the first entry, turn on IN_SEARCHME */
1387 		dnp->dn_instance = IN_SEARCHME;
1388 		dp->ind_next = mp;
1389 		dnp->dn_inlist = dp;
1390 		return;
1391 	}
1392 
1393 	ASSERT(mp->ind_instance != dp->ind_instance);
1394 	while (mp->ind_instance < dp->ind_instance && mp->ind_next) {
1395 		pp = mp;
1396 		mp = mp->ind_next;
1397 		ASSERT(mp->ind_instance != dp->ind_instance);
1398 	}
1399 
1400 	if (mp->ind_instance < dp->ind_instance) { /* end of list */
1401 		dp->ind_next = NULL;
1402 		mp->ind_next = dp;
1403 	} else {
1404 		dp->ind_next = pp->ind_next;
1405 		pp->ind_next = dp;
1406 	}
1407 }
1408 
1409 /*
1410  * Remove a driver entry from the list, given a previous pointer
1411  */
1412 static void
1413 in_removedrv(struct devnames *dnp, in_drv_t *mp)
1414 {
1415 	in_drv_t *dp;
1416 	in_drv_t *prevp;
1417 
1418 	if (dnp->dn_inlist == mp) {	/* head of list */
1419 		dnp->dn_inlist = mp->ind_next;
1420 		dnp->dn_instance = IN_SEARCHME;
1421 		in_dq_drv(mp);
1422 		in_dealloc_drv(mp);
1423 		return;
1424 	}
1425 	prevp = dnp->dn_inlist;
1426 	for (dp = prevp->ind_next; dp; dp = dp->ind_next) {
1427 		if (dp == mp) {		/* found it */
1428 			break;
1429 		}
1430 		prevp = dp;
1431 	}
1432 
1433 	ASSERT(dp == mp);
1434 	dnp->dn_instance = IN_SEARCHME;
1435 	prevp->ind_next = mp->ind_next;
1436 	in_dq_drv(mp);
1437 	in_dealloc_drv(mp);
1438 }
1439 
1440 static void
1441 in_dq_drv(in_drv_t *mp)
1442 {
1443 	struct in_node *node = mp->ind_node;
1444 	in_drv_t *ptr, *prev;
1445 
1446 	if (mp == node->in_drivers) {
1447 		node->in_drivers = mp->ind_next_drv;
1448 		return;
1449 	}
1450 	prev = node->in_drivers;
1451 	for (ptr = prev->ind_next_drv; ptr != (struct in_drv *)NULL;
1452 	    ptr = ptr->ind_next_drv) {
1453 		if (ptr == mp) {
1454 			prev->ind_next_drv = ptr->ind_next_drv;
1455 			return;
1456 		}
1457 		prev = ptr;
1458 	}
1459 	panic("in_dq_drv: in_drv not found on node driver list");
1460 }
1461 
1462 
1463 in_drv_t *
1464 in_drvwalk(in_node_t *np, char *binding_name)
1465 {
1466 	char *name;
1467 	in_drv_t *dp = np->in_drivers;
1468 	while (dp) {
1469 		if ((name = i_binding_to_drv_name(dp->ind_driver_name))
1470 		    == NULL) {
1471 			name = dp->ind_driver_name;
1472 		}
1473 		if (strcmp(binding_name, name) == 0) {
1474 			break;
1475 		}
1476 		dp = dp->ind_next_drv;
1477 	}
1478 	return (dp);
1479 }
1480 
1481 
1482 
1483 static void
1484 i_log_devfs_instance_mod(void)
1485 {
1486 	sysevent_t	*ev;
1487 	sysevent_id_t	eid;
1488 	static int	sent_one = 0;
1489 
1490 	/*
1491 	 * Prevent unnecessary event generation.  Do not generate more than
1492 	 * one event during boot.
1493 	 */
1494 	if (sent_one && !i_ddi_io_initialized())
1495 		return;
1496 
1497 	ev = sysevent_alloc(EC_DEVFS, ESC_DEVFS_INSTANCE_MOD, EP_DDI,
1498 	    SE_NOSLEEP);
1499 	if (ev == NULL) {
1500 		return;
1501 	}
1502 	if (log_sysevent(ev, SE_NOSLEEP, &eid) != 0) {
1503 		cmn_err(CE_WARN, "i_log_devfs_instance_mod: failed to post "
1504 		    "event");
1505 	} else {
1506 		sent_one = 1;
1507 	}
1508 	sysevent_free(ev);
1509 }
1510 
1511 void
1512 e_ddi_enter_instance(void)
1513 {
1514 	mutex_enter(&e_ddi_inst_state.ins_serial);
1515 	if (e_ddi_inst_state.ins_thread == curthread)
1516 		e_ddi_inst_state.ins_busy++;
1517 	else {
1518 		while (e_ddi_inst_state.ins_busy)
1519 			cv_wait(&e_ddi_inst_state.ins_serial_cv,
1520 			    &e_ddi_inst_state.ins_serial);
1521 		e_ddi_inst_state.ins_thread = curthread;
1522 		e_ddi_inst_state.ins_busy = 1;
1523 	}
1524 	mutex_exit(&e_ddi_inst_state.ins_serial);
1525 }
1526 
1527 void
1528 e_ddi_exit_instance(void)
1529 {
1530 	mutex_enter(&e_ddi_inst_state.ins_serial);
1531 	e_ddi_inst_state.ins_busy--;
1532 	if (e_ddi_inst_state.ins_busy == 0) {
1533 		cv_broadcast(&e_ddi_inst_state.ins_serial_cv);
1534 		e_ddi_inst_state.ins_thread = NULL;
1535 	}
1536 	mutex_exit(&e_ddi_inst_state.ins_serial);
1537 }
1538 
1539 int
1540 e_ddi_instance_is_clean(void)
1541 {
1542 	return (e_ddi_inst_state.ins_dirty == B_FALSE);
1543 }
1544 
1545 void
1546 e_ddi_instance_set_clean(void)
1547 {
1548 	e_ddi_inst_state.ins_dirty = B_FALSE;
1549 }
1550 
1551 in_node_t *
1552 e_ddi_instance_root(void)
1553 {
1554 	return (e_ddi_inst_state.ins_root);
1555 }
1556 
1557 /*
1558  * Visit a node in the instance tree
1559  */
1560 static int
1561 in_walk_instances(in_node_t *np, char *path, char *this,
1562     int (*f)(const char *, in_node_t *, in_drv_t *, void *), void *arg)
1563 {
1564 	in_drv_t *dp;
1565 	int rval = INST_WALK_CONTINUE;
1566 	char *next;
1567 
1568 	while (np != NULL) {
1569 
1570 		if (np->in_unit_addr[0] == 0)
1571 			(void) sprintf(this, "/%s", np->in_node_name);
1572 		else
1573 			(void) sprintf(this, "/%s@%s", np->in_node_name,
1574 			    np->in_unit_addr);
1575 		next = this + strlen(this);
1576 
1577 		for (dp = np->in_drivers; dp; dp = dp->ind_next_drv) {
1578 			if (dp->ind_state == IN_PERMANENT) {
1579 				rval = (*f)(path, np, dp, arg);
1580 				if (rval == INST_WALK_TERMINATE)
1581 					break;
1582 			}
1583 		}
1584 
1585 		if (np->in_child) {
1586 			rval = in_walk_instances(np->in_child,
1587 			    path, next, f, arg);
1588 			if (rval == INST_WALK_TERMINATE)
1589 				break;
1590 		}
1591 
1592 		np = np->in_sibling;
1593 	}
1594 
1595 	return (rval);
1596 }
1597 
1598 /*
1599  * A general interface for walking the instance tree,
1600  * calling a user-supplied callback for each node.
1601  */
1602 int
1603 e_ddi_walk_instances(int (*f)(const char *, in_node_t *, in_drv_t *, void *),
1604     void *arg)
1605 {
1606 	in_node_t *root;
1607 	int rval;
1608 	char *path;
1609 
1610 	path = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1611 
1612 	e_ddi_enter_instance();
1613 	root = e_ddi_instance_root();
1614 	rval = in_walk_instances(root->in_child, path, path, f, arg);
1615 
1616 	e_ddi_exit_instance();
1617 
1618 	kmem_free(path, MAXPATHLEN);
1619 	return (rval);
1620 }
1621 
1622 in_node_t *
1623 e_ddi_path_to_instance(char *path)
1624 {
1625 	in_node_t *np;
1626 
1627 	np = in_make_path(path);
1628 	if (np && np->in_drivers && np->in_drivers->ind_state == IN_PERMANENT) {
1629 		return (np);
1630 	}
1631 	return (NULL);
1632 }
1633 
1634 void
1635 e_ddi_borrow_instance(dev_info_t *cdip, in_node_t *cnp)
1636 {
1637 	char		*alias;
1638 	in_node_t	*anp;
1639 	char		*curr = kmem_alloc(MAXPATHLEN, KM_NOSLEEP);
1640 
1641 	if (curr == NULL) {
1642 		ddi_err(DER_PANIC, cdip, "curr alloc failed");
1643 		/*NOTREACHED*/
1644 	}
1645 
1646 	(void) ddi_pathname(cdip, curr);
1647 
1648 	if (cnp->in_drivers) {
1649 		/* there can be multiple drivers bound */
1650 		ddi_err(DER_LOG, cdip, "%s has previous binding: %s", curr,
1651 		    cnp->in_drivers->ind_driver_name);
1652 	}
1653 
1654 	alias = ddi_curr_redirect(curr);
1655 
1656 	/* bail here if the alias matches any other current path or itself */
1657 	if (alias && ((strcmp(curr, alias) == 0) ||
1658 	    (ddi_curr_redirect(alias) != 0))) {
1659 		DDI_MP_DBG((CE_NOTE, "not borrowing current: %s alias: %s",
1660 		    curr, alias));
1661 		goto out;
1662 	}
1663 
1664 	if (alias && (anp = e_ddi_path_to_instance(alias)) != NULL) {
1665 		/*
1666 		 * Since pcieb nodes can split and merge, it is dangerous
1667 		 * to borrow and instance for them. However since they do
1668 		 * not expose their instance numbers it is safe to never
1669 		 * borrow one.
1670 		 */
1671 		if (anp->in_drivers->ind_driver_name &&
1672 		    (strcmp(anp->in_drivers->ind_driver_name, "pcieb") == 0)) {
1673 			DDI_MP_DBG((CE_NOTE, "not borrowing pcieb: "
1674 			    "%s alias: %s", curr, alias));
1675 			goto out;
1676 		}
1677 		DDI_MP_DBG((CE_NOTE, "borrowing current: %s alias: %s",
1678 		    curr, alias));
1679 		cnp->in_drivers = anp->in_drivers;
1680 		anp->in_drivers = NULL;
1681 	}
1682 out:
1683 	kmem_free(curr, MAXPATHLEN);
1684 }
1685 
1686 void
1687 e_ddi_return_instance(dev_info_t *cdip, char *addr, in_node_t *cnp)
1688 {
1689 	in_node_t	*anp;
1690 	char		*alias;
1691 	char		*curr = kmem_alloc(MAXPATHLEN, KM_NOSLEEP);
1692 
1693 	if (curr == NULL) {
1694 		ddi_err(DER_PANIC, cdip, "alloc of curr failed");
1695 		/*NOTREACHED*/
1696 	}
1697 
1698 	(void) ddi_pathname(cdip, curr);
1699 	if (addr) {
1700 		(void) strlcat(curr, "@", MAXPATHLEN);
1701 		(void) strlcat(curr, addr, MAXPATHLEN);
1702 
1703 	}
1704 	if (cnp->in_drivers == NULL) {
1705 		ddi_err(DER_PANIC, cdip, "cnp has no inst: %p", cnp);
1706 		/*NOTREACHED*/
1707 	}
1708 
1709 	alias = ddi_curr_redirect(curr);
1710 	kmem_free(curr, MAXPATHLEN);
1711 
1712 	if (alias && (anp = e_ddi_path_to_instance(alias)) != NULL) {
1713 		ASSERT(anp->in_drivers == NULL);
1714 		anp->in_drivers = cnp->in_drivers;
1715 		cnp->in_drivers = NULL;
1716 	}
1717 }
1718