xref: /titanic_44/usr/src/uts/common/os/devid_cache.c (revision cb8a054b1ab30d5caa746e6c44f29d4c9d3071c1)
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) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <sys/note.h>
26 #include <sys/t_lock.h>
27 #include <sys/cmn_err.h>
28 #include <sys/instance.h>
29 #include <sys/conf.h>
30 #include <sys/stat.h>
31 #include <sys/ddi.h>
32 #include <sys/hwconf.h>
33 #include <sys/sunddi.h>
34 #include <sys/sunndi.h>
35 #include <sys/sunmdi.h>
36 #include <sys/ddi_impldefs.h>
37 #include <sys/ndi_impldefs.h>
38 #include <sys/kobj.h>
39 #include <sys/devcache.h>
40 #include <sys/devid_cache.h>
41 #include <sys/sysmacros.h>
42 
43 /*
44  * Discovery refers to the heroic effort made to discover a device which
45  * cannot be accessed at the physical path where it once resided.  Discovery
46  * involves walking the entire device tree attaching all possible disk
47  * instances, to search for the device referenced by a devid.  Obviously,
48  * full device discovery is something to be avoided where possible.
49  * Note that simply invoking devfsadm(1M) is equivalent to running full
50  * discovery at the devid cache level.
51  *
52  * Reasons why a disk may not be accessible:
53  *	disk powered off
54  *	disk removed or cable disconnected
55  *	disk or adapter broken
56  *
57  * Note that discovery is not needed and cannot succeed in any of these
58  * cases.
59  *
60  * When discovery may succeed:
61  *	Discovery will result in success when a device has been moved
62  *	to a different address.  Note that it's recommended that
63  *	devfsadm(1M) be invoked (no arguments required) whenever a system's
64  *	h/w configuration has been updated.  Alternatively, a
65  *	reconfiguration boot can be used to accomplish the same result.
66  *
67  * Note that discovery is not necessary to be able to correct an access
68  * failure for a device which was powered off.  Assuming the cache has an
69  * entry for such a device, simply powering it on should permit the system
70  * to access it.  If problems persist after powering it on, invoke
71  * devfsadm(1M).
72  *
73  * Discovery prior to mounting root is only of interest when booting
74  * from a filesystem which accesses devices by device id, which of
75  * not all do.
76  *
77  * Tunables
78  *
79  * devid_discovery_boot (default 1)
80  *	Number of times discovery will be attempted prior to mounting root.
81  *	Must be done at least once to recover from corrupted or missing
82  *	devid cache backing store.  Probably there's no reason to ever
83  *	set this to greater than one as a missing device will remain
84  *	unavailable no matter how often the system searches for it.
85  *
86  * devid_discovery_postboot (default 1)
87  *	Number of times discovery will be attempted after mounting root.
88  *	This must be performed at least once to discover any devices
89  *	needed after root is mounted which may have been powered
90  *	off and moved before booting.
91  *	Setting this to a larger positive number will introduce
92  *	some inconsistency in system operation.  Searching for a device
93  *	will take an indeterminate amount of time, sometimes slower,
94  *	sometimes faster.  In addition, the system will sometimes
95  *	discover a newly powered on device, sometimes it won't.
96  *	Use of this option is not therefore recommended.
97  *
98  * devid_discovery_postboot_always (default 0)
99  *	Set to 1, the system will always attempt full discovery.
100  *
101  * devid_discovery_secs (default 0)
102  *	Set to a positive value, the system will attempt full discovery
103  *	but with a minimum delay between attempts.  A device search
104  *	within the period of time specified will result in failure.
105  *
106  * devid_cache_read_disable (default 0)
107  *	Set to 1 to disable reading /etc/devices/devid_cache.
108  *	Devid cache will continue to operate normally but
109  *	at least one discovery attempt will be required.
110  *
111  * devid_cache_write_disable (default 0)
112  *	Set to 1 to disable updates to /etc/devices/devid_cache.
113  *	Any updates to the devid cache will not be preserved across a reboot.
114  *
115  * devid_report_error (default 0)
116  *	Set to 1 to enable some error messages related to devid
117  *	cache failures.
118  *
119  * The devid is packed in the cache file as a byte array.  For
120  * portability, this could be done in the encoded string format.
121  */
122 
123 
124 int devid_discovery_boot = 1;
125 int devid_discovery_postboot = 1;
126 int devid_discovery_postboot_always = 0;
127 int devid_discovery_secs = 0;
128 
129 int devid_cache_read_disable = 0;
130 int devid_cache_write_disable = 0;
131 
132 int devid_report_error = 0;
133 
134 
135 /*
136  * State to manage discovery of devices providing a devid
137  */
138 static int		devid_discovery_busy = 0;
139 static kmutex_t		devid_discovery_mutex;
140 static kcondvar_t	devid_discovery_cv;
141 static clock_t		devid_last_discovery = 0;
142 
143 
144 #ifdef	DEBUG
145 int nvp_devid_debug = 0;
146 int devid_debug = 0;
147 int devid_log_registers = 0;
148 int devid_log_finds = 0;
149 int devid_log_lookups = 0;
150 int devid_log_discovery = 0;
151 int devid_log_matches = 0;
152 int devid_log_paths = 0;
153 int devid_log_failures = 0;
154 int devid_log_hold = 0;
155 int devid_log_unregisters = 0;
156 int devid_log_removes = 0;
157 int devid_register_debug = 0;
158 int devid_log_stale = 0;
159 int devid_log_detaches = 0;
160 #endif	/* DEBUG */
161 
162 /*
163  * devid cache file registration for cache reads and updates
164  */
165 static nvf_ops_t devid_cache_ops = {
166 	"/etc/devices/devid_cache",		/* path to cache */
167 	devid_cache_unpack_nvlist,		/* read: nvlist to nvp */
168 	devid_cache_pack_list,			/* write: nvp to nvlist */
169 	devid_list_free,			/* free data list */
170 	NULL					/* write complete callback */
171 };
172 
173 /*
174  * handle to registered devid cache handlers
175  */
176 nvf_handle_t	dcfd_handle;
177 
178 
179 /*
180  * Initialize devid cache file management
181  */
182 void
183 devid_cache_init(void)
184 {
185 	dcfd_handle = nvf_register_file(&devid_cache_ops);
186 	ASSERT(dcfd_handle);
187 
188 	list_create(nvf_list(dcfd_handle), sizeof (nvp_devid_t),
189 	    offsetof(nvp_devid_t, nvp_link));
190 
191 	mutex_init(&devid_discovery_mutex, NULL, MUTEX_DEFAULT, NULL);
192 	cv_init(&devid_discovery_cv, NULL, CV_DRIVER, NULL);
193 }
194 
195 /*
196  * Read and initialize the devid cache from the persistent store
197  */
198 void
199 devid_cache_read(void)
200 {
201 	if (!devid_cache_read_disable) {
202 		rw_enter(nvf_lock(dcfd_handle), RW_WRITER);
203 		ASSERT(list_head(nvf_list(dcfd_handle)) == NULL);
204 		(void) nvf_read_file(dcfd_handle);
205 		rw_exit(nvf_lock(dcfd_handle));
206 	}
207 }
208 
209 static void
210 devid_nvp_free(nvp_devid_t *dp)
211 {
212 	if (dp->nvp_devpath)
213 		kmem_free(dp->nvp_devpath, strlen(dp->nvp_devpath)+1);
214 	if (dp->nvp_devid)
215 		kmem_free(dp->nvp_devid, ddi_devid_sizeof(dp->nvp_devid));
216 
217 	kmem_free(dp, sizeof (nvp_devid_t));
218 }
219 
220 static void
221 devid_list_free(nvf_handle_t fd)
222 {
223 	list_t		*listp;
224 	nvp_devid_t	*np;
225 
226 	ASSERT(RW_WRITE_HELD(nvf_lock(dcfd_handle)));
227 
228 	listp = nvf_list(fd);
229 	while (np = list_head(listp)) {
230 		list_remove(listp, np);
231 		devid_nvp_free(np);
232 	}
233 }
234 
235 /*
236  * Free an nvp element in a list
237  */
238 static void
239 devid_nvp_unlink_and_free(nvf_handle_t fd, nvp_devid_t *np)
240 {
241 	list_remove(nvf_list(fd), np);
242 	devid_nvp_free(np);
243 }
244 
245 /*
246  * Unpack a device path/nvlist pair to the list of devid cache elements.
247  * Used to parse the nvlist format when reading
248  * /etc/devices/devid_cache
249  */
250 static int
251 devid_cache_unpack_nvlist(nvf_handle_t fd, nvlist_t *nvl, char *name)
252 {
253 	nvp_devid_t *np;
254 	ddi_devid_t devidp;
255 	int rval;
256 	uint_t n;
257 
258 	NVP_DEVID_DEBUG_PATH((name));
259 	ASSERT(RW_WRITE_HELD(nvf_lock(dcfd_handle)));
260 
261 	/*
262 	 * check path for a devid
263 	 */
264 	rval = nvlist_lookup_byte_array(nvl,
265 	    DP_DEVID_ID, (uchar_t **)&devidp, &n);
266 	if (rval == 0) {
267 		if (ddi_devid_valid(devidp) == DDI_SUCCESS) {
268 			ASSERT(n == ddi_devid_sizeof(devidp));
269 			np = kmem_zalloc(sizeof (nvp_devid_t), KM_SLEEP);
270 			np->nvp_devpath = i_ddi_strdup(name, KM_SLEEP);
271 			np->nvp_devid = kmem_alloc(n, KM_SLEEP);
272 			(void) bcopy(devidp, np->nvp_devid, n);
273 			list_insert_tail(nvf_list(fd), np);
274 			NVP_DEVID_DEBUG_DEVID((np->nvp_devid));
275 		} else {
276 			DEVIDERR((CE_CONT,
277 			    "%s: invalid devid\n", name));
278 		}
279 	} else {
280 		DEVIDERR((CE_CONT,
281 		    "%s: devid not available\n", name));
282 	}
283 
284 	return (0);
285 }
286 
287 /*
288  * Pack the list of devid cache elements into a single nvlist
289  * Used when writing the nvlist file.
290  */
291 static int
292 devid_cache_pack_list(nvf_handle_t fd, nvlist_t **ret_nvl)
293 {
294 	nvlist_t	*nvl, *sub_nvl;
295 	nvp_devid_t	*np;
296 	int		rval;
297 	list_t		*listp;
298 
299 	ASSERT(RW_WRITE_HELD(nvf_lock(dcfd_handle)));
300 
301 	rval = nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP);
302 	if (rval != 0) {
303 		nvf_error("%s: nvlist alloc error %d\n",
304 		    nvf_cache_name(fd), rval);
305 		return (DDI_FAILURE);
306 	}
307 
308 	listp = nvf_list(fd);
309 	for (np = list_head(listp); np; np = list_next(listp, np)) {
310 		if (np->nvp_devid == NULL)
311 			continue;
312 		NVP_DEVID_DEBUG_PATH(np->nvp_devpath);
313 		rval = nvlist_alloc(&sub_nvl, NV_UNIQUE_NAME, KM_SLEEP);
314 		if (rval != 0) {
315 			nvf_error("%s: nvlist alloc error %d\n",
316 			    nvf_cache_name(fd), rval);
317 			sub_nvl = NULL;
318 			goto err;
319 		}
320 
321 		rval = nvlist_add_byte_array(sub_nvl, DP_DEVID_ID,
322 		    (uchar_t *)np->nvp_devid,
323 		    ddi_devid_sizeof(np->nvp_devid));
324 		if (rval == 0) {
325 			NVP_DEVID_DEBUG_DEVID(np->nvp_devid);
326 		} else {
327 			nvf_error(
328 			    "%s: nvlist add error %d (devid)\n",
329 			    nvf_cache_name(fd), rval);
330 			goto err;
331 		}
332 
333 		rval = nvlist_add_nvlist(nvl, np->nvp_devpath, sub_nvl);
334 		if (rval != 0) {
335 			nvf_error("%s: nvlist add error %d (sublist)\n",
336 			    nvf_cache_name(fd), rval);
337 			goto err;
338 		}
339 		nvlist_free(sub_nvl);
340 	}
341 
342 	*ret_nvl = nvl;
343 	return (DDI_SUCCESS);
344 
345 err:
346 	if (sub_nvl)
347 		nvlist_free(sub_nvl);
348 	nvlist_free(nvl);
349 	*ret_nvl = NULL;
350 	return (DDI_FAILURE);
351 }
352 
353 static int
354 e_devid_do_discovery(void)
355 {
356 	ASSERT(mutex_owned(&devid_discovery_mutex));
357 
358 	if (i_ddi_io_initialized() == 0) {
359 		if (devid_discovery_boot > 0) {
360 			devid_discovery_boot--;
361 			return (1);
362 		}
363 	} else {
364 		if (devid_discovery_postboot_always > 0)
365 			return (1);
366 		if (devid_discovery_postboot > 0) {
367 			devid_discovery_postboot--;
368 			return (1);
369 		}
370 		if (devid_discovery_secs > 0) {
371 			if ((ddi_get_lbolt() - devid_last_discovery) >
372 			    drv_usectohz(devid_discovery_secs * MICROSEC)) {
373 				return (1);
374 			}
375 		}
376 	}
377 
378 	DEVID_LOG_DISC((CE_CONT, "devid_discovery: no discovery\n"));
379 	return (0);
380 }
381 
382 static void
383 e_ddi_devid_hold_by_major(major_t major)
384 {
385 	DEVID_LOG_DISC((CE_CONT,
386 	    "devid_discovery: ddi_hold_installed_driver %d\n", major));
387 
388 	if (ddi_hold_installed_driver(major) == NULL)
389 		return;
390 
391 	ddi_rele_driver(major);
392 }
393 
394 static char *e_ddi_devid_hold_driver_list[] = { "sd", "ssd", "dad" };
395 
396 #define	N_DRIVERS_TO_HOLD	\
397 	(sizeof (e_ddi_devid_hold_driver_list) / sizeof (char *))
398 
399 
400 static void
401 e_ddi_devid_hold_installed_driver(ddi_devid_t devid)
402 {
403 	impl_devid_t	*id = (impl_devid_t *)devid;
404 	major_t		major, hint_major;
405 	char		hint[DEVID_HINT_SIZE + 1];
406 	char		**drvp;
407 	int		i;
408 
409 	/* Count non-null bytes */
410 	for (i = 0; i < DEVID_HINT_SIZE; i++)
411 		if (id->did_driver[i] == '\0')
412 			break;
413 
414 	/* Make a copy of the driver hint */
415 	bcopy(id->did_driver, hint, i);
416 	hint[i] = '\0';
417 
418 	/* search for the devid using the hint driver */
419 	hint_major = ddi_name_to_major(hint);
420 	if (hint_major != DDI_MAJOR_T_NONE) {
421 		e_ddi_devid_hold_by_major(hint_major);
422 	}
423 
424 	drvp = e_ddi_devid_hold_driver_list;
425 	for (i = 0; i < N_DRIVERS_TO_HOLD; i++, drvp++) {
426 		major = ddi_name_to_major(*drvp);
427 		if (major != DDI_MAJOR_T_NONE && major != hint_major) {
428 			e_ddi_devid_hold_by_major(major);
429 		}
430 	}
431 }
432 
433 
434 /*
435  * Return success if discovery was attempted, to indicate
436  * that the desired device may now be available.
437  */
438 int
439 e_ddi_devid_discovery(ddi_devid_t devid)
440 {
441 	int flags;
442 	int rval = DDI_SUCCESS;
443 
444 	mutex_enter(&devid_discovery_mutex);
445 
446 	if (devid_discovery_busy) {
447 		DEVID_LOG_DISC((CE_CONT, "devid_discovery: busy\n"));
448 		while (devid_discovery_busy) {
449 			cv_wait(&devid_discovery_cv, &devid_discovery_mutex);
450 		}
451 	} else if (e_devid_do_discovery()) {
452 		devid_discovery_busy = 1;
453 		mutex_exit(&devid_discovery_mutex);
454 
455 		if (i_ddi_io_initialized() == 0) {
456 			e_ddi_devid_hold_installed_driver(devid);
457 		} else {
458 			DEVID_LOG_DISC((CE_CONT,
459 			    "devid_discovery: ndi_devi_config\n"));
460 			flags = NDI_DEVI_PERSIST | NDI_CONFIG | NDI_NO_EVENT;
461 			if (i_ddi_io_initialized())
462 				flags |= NDI_DRV_CONF_REPROBE;
463 			(void) ndi_devi_config(ddi_root_node(), flags);
464 		}
465 
466 		mutex_enter(&devid_discovery_mutex);
467 		devid_discovery_busy = 0;
468 		cv_broadcast(&devid_discovery_cv);
469 		if (devid_discovery_secs > 0)
470 			devid_last_discovery = ddi_get_lbolt();
471 		DEVID_LOG_DISC((CE_CONT, "devid_discovery: done\n"));
472 	} else {
473 		rval = DDI_FAILURE;
474 		DEVID_LOG_DISC((CE_CONT, "no devid discovery\n"));
475 	}
476 
477 	mutex_exit(&devid_discovery_mutex);
478 
479 	return (rval);
480 }
481 
482 /*
483  * As part of registering a devid for a device,
484  * update the devid cache with this device/devid pair
485  * or note that this combination has registered.
486  *
487  * If a devpath is provided it will be used as the path to register the
488  * devid against, otherwise we use ddi_pathname(dip).  In both cases
489  * we duplicate the path string so that it can be cached/freed indepdently
490  * of the original owner.
491  */
492 static int
493 e_devid_cache_register_cmn(dev_info_t *dip, ddi_devid_t devid, char *devpath)
494 {
495 	nvp_devid_t *np;
496 	nvp_devid_t *new_nvp;
497 	ddi_devid_t new_devid;
498 	int new_devid_size;
499 	char *path, *fullpath;
500 	ddi_devid_t free_devid = NULL;
501 	int pathlen;
502 	list_t *listp;
503 	int is_dirty = 0;
504 
505 
506 	ASSERT(ddi_devid_valid(devid) == DDI_SUCCESS);
507 
508 	if (devpath) {
509 		pathlen = strlen(devpath) + 1;
510 		path = kmem_alloc(pathlen, KM_SLEEP);
511 		bcopy(devpath, path, pathlen);
512 	} else {
513 		/*
514 		 * We are willing to accept DS_BOUND nodes if we can form a full
515 		 * ddi_pathname (i.e. the node is part way to becomming
516 		 * DS_INITIALIZED and devi_addr/ddi_get_name_addr are non-NULL).
517 		 */
518 		if (ddi_get_name_addr(dip) == NULL)
519 			return (DDI_FAILURE);
520 
521 		fullpath = kmem_alloc(MAXPATHLEN, KM_SLEEP);
522 		(void) ddi_pathname(dip, fullpath);
523 		pathlen = strlen(fullpath) + 1;
524 		path = kmem_alloc(pathlen, KM_SLEEP);
525 		bcopy(fullpath, path, pathlen);
526 		kmem_free(fullpath, MAXPATHLEN);
527 	}
528 
529 	DEVID_LOG_REG(("register", devid, path));
530 
531 	new_nvp = kmem_zalloc(sizeof (nvp_devid_t), KM_SLEEP);
532 	new_devid_size = ddi_devid_sizeof(devid);
533 	new_devid = kmem_alloc(new_devid_size, KM_SLEEP);
534 	(void) bcopy(devid, new_devid, new_devid_size);
535 
536 	rw_enter(nvf_lock(dcfd_handle), RW_WRITER);
537 
538 	listp = nvf_list(dcfd_handle);
539 	for (np = list_head(listp); np; np = list_next(listp, np)) {
540 		if (strcmp(path, np->nvp_devpath) == 0) {
541 			DEVID_DEBUG2((CE_CONT,
542 			    "register: %s path match\n", path));
543 			if (np->nvp_devid == NULL) {
544 replace:			np->nvp_devid = new_devid;
545 				np->nvp_flags |=
546 				    NVP_DEVID_DIP | NVP_DEVID_REGISTERED;
547 				np->nvp_dip = dip;
548 				if (!devid_cache_write_disable) {
549 					nvf_mark_dirty(dcfd_handle);
550 					is_dirty = 1;
551 				}
552 				rw_exit(nvf_lock(dcfd_handle));
553 				kmem_free(new_nvp, sizeof (nvp_devid_t));
554 				kmem_free(path, pathlen);
555 				goto exit;
556 			}
557 			if (ddi_devid_valid(np->nvp_devid) != DDI_SUCCESS) {
558 				/* replace invalid devid */
559 				free_devid = np->nvp_devid;
560 				goto replace;
561 			}
562 			/*
563 			 * We're registering an already-cached path
564 			 * Does the device's devid match the cache?
565 			 */
566 			if (ddi_devid_compare(devid, np->nvp_devid) != 0) {
567 				DEVID_DEBUG((CE_CONT, "devid register: "
568 				    "devid %s does not match\n", path));
569 				/*
570 				 * Replace cached devid for this path
571 				 * with newly registered devid.  A devid
572 				 * may map to multiple paths but one path
573 				 * should only map to one devid.
574 				 */
575 				devid_nvp_unlink_and_free(dcfd_handle, np);
576 				np = NULL;
577 				break;
578 			} else {
579 				DEVID_DEBUG2((CE_CONT,
580 				    "devid register: %s devid match\n", path));
581 				np->nvp_flags |=
582 				    NVP_DEVID_DIP | NVP_DEVID_REGISTERED;
583 				np->nvp_dip = dip;
584 				rw_exit(nvf_lock(dcfd_handle));
585 				kmem_free(new_nvp, sizeof (nvp_devid_t));
586 				kmem_free(path, pathlen);
587 				kmem_free(new_devid, new_devid_size);
588 				return (DDI_SUCCESS);
589 			}
590 		}
591 	}
592 
593 	/*
594 	 * Add newly registered devid to the cache
595 	 */
596 	ASSERT(np == NULL);
597 
598 	new_nvp->nvp_devpath = path;
599 	new_nvp->nvp_flags = NVP_DEVID_DIP | NVP_DEVID_REGISTERED;
600 	new_nvp->nvp_dip = dip;
601 	new_nvp->nvp_devid = new_devid;
602 
603 	if (!devid_cache_write_disable) {
604 		is_dirty = 1;
605 		nvf_mark_dirty(dcfd_handle);
606 	}
607 	list_insert_tail(nvf_list(dcfd_handle), new_nvp);
608 
609 	rw_exit(nvf_lock(dcfd_handle));
610 
611 exit:
612 	if (free_devid)
613 		kmem_free(free_devid, ddi_devid_sizeof(free_devid));
614 
615 	if (is_dirty)
616 		nvf_wake_daemon();
617 
618 	return (DDI_SUCCESS);
619 }
620 
621 int
622 e_devid_cache_register(dev_info_t *dip, ddi_devid_t devid)
623 {
624 	return (e_devid_cache_register_cmn(dip, devid, NULL));
625 }
626 
627 /*
628  * Unregister a device's devid; the devinfo may hit on multiple entries
629  * arising from both pHCI and vHCI paths.
630  * Called as an instance detachs.
631  * Invalidate the devid's devinfo reference.
632  * Devid-path remains in the cache.
633  */
634 
635 void
636 e_devid_cache_unregister(dev_info_t *dip)
637 {
638 	nvp_devid_t *np;
639 	list_t *listp;
640 
641 	rw_enter(nvf_lock(dcfd_handle), RW_WRITER);
642 
643 	listp = nvf_list(dcfd_handle);
644 	for (np = list_head(listp); np; np = list_next(listp, np)) {
645 		if (np->nvp_devid == NULL)
646 			continue;
647 		if ((np->nvp_flags & NVP_DEVID_DIP) && np->nvp_dip == dip) {
648 			DEVID_LOG_UNREG((CE_CONT,
649 			    "unregister: %s\n", np->nvp_devpath));
650 			np->nvp_flags &= ~NVP_DEVID_DIP;
651 			np->nvp_dip = NULL;
652 		}
653 	}
654 
655 	rw_exit(nvf_lock(dcfd_handle));
656 }
657 
658 int
659 e_devid_cache_pathinfo(mdi_pathinfo_t *pip, ddi_devid_t devid)
660 {
661 	char *path = mdi_pi_pathname(pip);
662 
663 	return (e_devid_cache_register_cmn(mdi_pi_get_client(pip), devid,
664 	    path));
665 }
666 
667 /*
668  * Purge devid cache of stale devids
669  */
670 void
671 devid_cache_cleanup(void)
672 {
673 	nvp_devid_t *np, *next;
674 	list_t *listp;
675 	int is_dirty = 0;
676 
677 	rw_enter(nvf_lock(dcfd_handle), RW_WRITER);
678 
679 	listp = nvf_list(dcfd_handle);
680 	for (np = list_head(listp); np; np = next) {
681 		next = list_next(listp, np);
682 		if (np->nvp_devid == NULL)
683 			continue;
684 		if ((np->nvp_flags & NVP_DEVID_REGISTERED) == 0) {
685 			DEVID_LOG_REMOVE((CE_CONT,
686 			    "cleanup: %s\n", np->nvp_devpath));
687 			if (!devid_cache_write_disable) {
688 				nvf_mark_dirty(dcfd_handle);
689 				is_dirty = 0;
690 			}
691 			devid_nvp_unlink_and_free(dcfd_handle, np);
692 		}
693 	}
694 
695 	rw_exit(nvf_lock(dcfd_handle));
696 
697 	if (is_dirty)
698 		nvf_wake_daemon();
699 }
700 
701 
702 /*
703  * Build a list of dev_t's for a device/devid
704  *
705  * The effect of this function is cumulative, adding dev_t's
706  * for the device to the list of all dev_t's for a given
707  * devid.
708  */
709 static void
710 e_devid_minor_to_devlist(
711 	dev_info_t	*dip,
712 	char		*minor_name,
713 	int		ndevts_alloced,
714 	int		*devtcntp,
715 	dev_t		*devtsp)
716 {
717 	int			circ;
718 	struct ddi_minor_data	*dmdp;
719 	int			minor_all = 0;
720 	int			ndevts = *devtcntp;
721 
722 	ASSERT(i_ddi_devi_attached(dip));
723 
724 	/* are we looking for a set of minor nodes? */
725 	if ((minor_name == DEVID_MINOR_NAME_ALL) ||
726 	    (minor_name == DEVID_MINOR_NAME_ALL_CHR) ||
727 	    (minor_name == DEVID_MINOR_NAME_ALL_BLK))
728 		minor_all = 1;
729 
730 	/* Find matching minor names */
731 	ndi_devi_enter(dip, &circ);
732 	for (dmdp = DEVI(dip)->devi_minor; dmdp; dmdp = dmdp->next) {
733 
734 		/* Skip non-minors, and non matching minor names */
735 		if ((dmdp->type != DDM_MINOR) || ((minor_all == 0) &&
736 		    strcmp(dmdp->ddm_name, minor_name)))
737 			continue;
738 
739 		/* filter out minor_all mismatches */
740 		if (minor_all &&
741 		    (((minor_name == DEVID_MINOR_NAME_ALL_CHR) &&
742 		    (dmdp->ddm_spec_type != S_IFCHR)) ||
743 		    ((minor_name == DEVID_MINOR_NAME_ALL_BLK) &&
744 		    (dmdp->ddm_spec_type != S_IFBLK))))
745 			continue;
746 
747 		if (ndevts < ndevts_alloced)
748 			devtsp[ndevts] = dmdp->ddm_dev;
749 		ndevts++;
750 	}
751 	ndi_devi_exit(dip, circ);
752 
753 	*devtcntp = ndevts;
754 }
755 
756 /*
757  * Search for cached entries matching a devid
758  * Return two lists:
759  *	a list of dev_info nodes, for those devices in the attached state
760  *	a list of pathnames whose instances registered the given devid
761  * If the lists passed in are not sufficient to return the matching
762  * references, return the size of lists required.
763  * The dev_info nodes are returned with a hold that the caller must release.
764  */
765 static int
766 e_devid_cache_devi_path_lists(ddi_devid_t devid, int retmax,
767 	int *retndevis, dev_info_t **retdevis, int *retnpaths, char **retpaths)
768 {
769 	nvp_devid_t *np;
770 	int ndevis, npaths;
771 	dev_info_t *dip, *pdip;
772 	int circ;
773 	int maxdevis = 0;
774 	int maxpaths = 0;
775 	list_t *listp;
776 
777 	ndevis = 0;
778 	npaths = 0;
779 	listp = nvf_list(dcfd_handle);
780 	for (np = list_head(listp); np; np = list_next(listp, np)) {
781 		if (np->nvp_devid == NULL)
782 			continue;
783 		if (ddi_devid_valid(np->nvp_devid) != DDI_SUCCESS) {
784 			DEVIDERR((CE_CONT,
785 			    "find: invalid devid %s\n",
786 			    np->nvp_devpath));
787 			continue;
788 		}
789 		if (ddi_devid_compare(devid, np->nvp_devid) == 0) {
790 			DEVID_DEBUG2((CE_CONT,
791 			    "find: devid match: %s 0x%x\n",
792 			    np->nvp_devpath, np->nvp_flags));
793 			DEVID_LOG_MATCH(("find", devid, np->nvp_devpath));
794 			DEVID_LOG_PATHS((CE_CONT, "%s\n", np->nvp_devpath));
795 
796 			/*
797 			 * Check if we have a cached devinfo reference for this
798 			 * devid.  Place a hold on it to prevent detach
799 			 * Otherwise, use the path instead.
800 			 * Note: returns with a hold on each dev_info
801 			 * node in the list.
802 			 */
803 			dip = NULL;
804 			if (np->nvp_flags & NVP_DEVID_DIP) {
805 				pdip = ddi_get_parent(np->nvp_dip);
806 				if (ndi_devi_tryenter(pdip, &circ)) {
807 					dip = np->nvp_dip;
808 					ndi_hold_devi(dip);
809 					ndi_devi_exit(pdip, circ);
810 					ASSERT(!DEVI_IS_ATTACHING(dip));
811 					ASSERT(!DEVI_IS_DETACHING(dip));
812 				} else {
813 					DEVID_LOG_DETACH((CE_CONT,
814 					    "may be detaching: %s\n",
815 					    np->nvp_devpath));
816 				}
817 			}
818 
819 			if (dip) {
820 				if (ndevis < retmax) {
821 					retdevis[ndevis++] = dip;
822 				} else {
823 					ndi_rele_devi(dip);
824 				}
825 				maxdevis++;
826 			} else {
827 				if (npaths < retmax)
828 					retpaths[npaths++] = np->nvp_devpath;
829 				maxpaths++;
830 			}
831 		}
832 	}
833 
834 	*retndevis = ndevis;
835 	*retnpaths = npaths;
836 	return (maxdevis > maxpaths ? maxdevis : maxpaths);
837 }
838 
839 
840 /*
841  * Search the devid cache, returning dev_t list for all
842  * device paths mapping to the device identified by the
843  * given devid.
844  *
845  * Primary interface used by ddi_lyr_devid_to_devlist()
846  */
847 int
848 e_devid_cache_to_devt_list(ddi_devid_t devid, char *minor_name,
849 	int *retndevts, dev_t **retdevts)
850 {
851 	char		*path, **paths;
852 	int		i, j, n;
853 	dev_t		*devts, *udevts;
854 	dev_t		tdevt;
855 	int		ndevts, undevts, ndevts_alloced;
856 	dev_info_t	*devi, **devis;
857 	int		ndevis, npaths, nalloced;
858 	ddi_devid_t	match_devid;
859 
860 	DEVID_LOG_FIND(("find", devid, NULL));
861 
862 	ASSERT(ddi_devid_valid(devid) == DDI_SUCCESS);
863 	if (ddi_devid_valid(devid) != DDI_SUCCESS) {
864 		DEVID_LOG_ERR(("invalid devid", devid, NULL));
865 		return (DDI_FAILURE);
866 	}
867 
868 	nalloced = 128;
869 
870 	for (;;) {
871 		paths = kmem_zalloc(nalloced * sizeof (char *), KM_SLEEP);
872 		devis = kmem_zalloc(nalloced * sizeof (dev_info_t *), KM_SLEEP);
873 
874 		rw_enter(nvf_lock(dcfd_handle), RW_READER);
875 		n = e_devid_cache_devi_path_lists(devid, nalloced,
876 		    &ndevis, devis, &npaths, paths);
877 		if (n <= nalloced)
878 			break;
879 		rw_exit(nvf_lock(dcfd_handle));
880 		for (i = 0; i < ndevis; i++)
881 			ndi_rele_devi(devis[i]);
882 		kmem_free(paths, nalloced * sizeof (char *));
883 		kmem_free(devis, nalloced * sizeof (dev_info_t *));
884 		nalloced = n + 128;
885 	}
886 
887 	for (i = 0; i < npaths; i++) {
888 		path = i_ddi_strdup(paths[i], KM_SLEEP);
889 		paths[i] = path;
890 	}
891 	rw_exit(nvf_lock(dcfd_handle));
892 
893 	if (ndevis == 0 && npaths == 0) {
894 		DEVID_LOG_ERR(("no devid found", devid, NULL));
895 		kmem_free(paths, nalloced * sizeof (char *));
896 		kmem_free(devis, nalloced * sizeof (dev_info_t *));
897 		return (DDI_FAILURE);
898 	}
899 
900 	ndevts_alloced = 128;
901 restart:
902 	ndevts = 0;
903 	devts = kmem_alloc(ndevts_alloced * sizeof (dev_t), KM_SLEEP);
904 	for (i = 0; i < ndevis; i++) {
905 		ASSERT(!DEVI_IS_ATTACHING(devis[i]));
906 		ASSERT(!DEVI_IS_DETACHING(devis[i]));
907 		e_devid_minor_to_devlist(devis[i], minor_name,
908 		    ndevts_alloced, &ndevts, devts);
909 		if (ndevts > ndevts_alloced) {
910 			kmem_free(devts, ndevts_alloced * sizeof (dev_t));
911 			ndevts_alloced += 128;
912 			goto restart;
913 		}
914 	}
915 	for (i = 0; i < npaths; i++) {
916 		DEVID_LOG_LOOKUP((CE_CONT, "lookup %s\n", paths[i]));
917 		devi = e_ddi_hold_devi_by_path(paths[i], 0);
918 		if (devi == NULL) {
919 			DEVID_LOG_STALE(("stale device reference",
920 			    devid, paths[i]));
921 			continue;
922 		}
923 		/*
924 		 * Verify the newly attached device registered a matching devid
925 		 */
926 		if (i_ddi_devi_get_devid(DDI_DEV_T_ANY, devi,
927 		    &match_devid) != DDI_SUCCESS) {
928 			DEVIDERR((CE_CONT,
929 			    "%s: no devid registered on attach\n",
930 			    paths[i]));
931 			ddi_release_devi(devi);
932 			continue;
933 		}
934 
935 		if (ddi_devid_compare(devid, match_devid) != 0) {
936 			DEVID_LOG_STALE(("new devid registered",
937 			    devid, paths[i]));
938 			ddi_release_devi(devi);
939 			ddi_devid_free(match_devid);
940 			continue;
941 		}
942 		ddi_devid_free(match_devid);
943 
944 		e_devid_minor_to_devlist(devi, minor_name,
945 		    ndevts_alloced, &ndevts, devts);
946 		ddi_release_devi(devi);
947 		if (ndevts > ndevts_alloced) {
948 			kmem_free(devts,
949 			    ndevts_alloced * sizeof (dev_t));
950 			ndevts_alloced += 128;
951 			goto restart;
952 		}
953 	}
954 
955 	/* drop hold from e_devid_cache_devi_path_lists */
956 	for (i = 0; i < ndevis; i++) {
957 		ndi_rele_devi(devis[i]);
958 	}
959 	for (i = 0; i < npaths; i++) {
960 		kmem_free(paths[i], strlen(paths[i]) + 1);
961 	}
962 	kmem_free(paths, nalloced * sizeof (char *));
963 	kmem_free(devis, nalloced * sizeof (dev_info_t *));
964 
965 	if (ndevts == 0) {
966 		DEVID_LOG_ERR(("no devid found", devid, NULL));
967 		kmem_free(devts, ndevts_alloced * sizeof (dev_t));
968 		return (DDI_FAILURE);
969 	}
970 
971 	/*
972 	 * Build the final list of sorted dev_t's with duplicates collapsed so
973 	 * returned results are consistent. This prevents implementation
974 	 * artifacts from causing unnecessary changes in SVM namespace.
975 	 */
976 	/* bubble sort */
977 	for (i = 0; i < (ndevts - 1); i++) {
978 		for (j = 0; j < ((ndevts - 1) - i); j++) {
979 			if (devts[j + 1] < devts[j]) {
980 				tdevt = devts[j];
981 				devts[j] = devts[j + 1];
982 				devts[j + 1] = tdevt;
983 			}
984 		}
985 	}
986 
987 	/* determine number of unique values */
988 	for (undevts = ndevts, i = 1; i < ndevts; i++) {
989 		if (devts[i - 1] == devts[i])
990 			undevts--;
991 	}
992 
993 	/* allocate unique */
994 	udevts = kmem_alloc(undevts * sizeof (dev_t), KM_SLEEP);
995 
996 	/* copy unique */
997 	udevts[0] = devts[0];
998 	for (i = 1, j = 1; i < ndevts; i++) {
999 		if (devts[i - 1] != devts[i])
1000 			udevts[j++] = devts[i];
1001 	}
1002 	ASSERT(j == undevts);
1003 
1004 	kmem_free(devts, ndevts_alloced * sizeof (dev_t));
1005 
1006 	*retndevts = undevts;
1007 	*retdevts = udevts;
1008 
1009 	return (DDI_SUCCESS);
1010 }
1011 
1012 void
1013 e_devid_cache_free_devt_list(int ndevts, dev_t *devt_list)
1014 {
1015 	kmem_free(devt_list, ndevts * sizeof (dev_t *));
1016 }
1017 
1018 /*
1019  * If given a full path and NULL ua, search for a cache entry
1020  * whose path matches the full path.  On a cache hit duplicate the
1021  * devid of the matched entry into the given devid (caller
1022  * must free);  nodenamebuf is not touched for this usage.
1023  *
1024  * Given a path and a non-NULL unit address, search the cache for any entry
1025  * matching "<path>/%@<unit-address>" where '%' is a wildcard meaning
1026  * any node name.  The path should not end a '/'.  On a cache hit
1027  * duplicate the devid as before (caller must free) and copy into
1028  * the caller-provided nodenamebuf (if not NULL) the nodename of the
1029  * matched entry.
1030  *
1031  * We must not make use of nvp_dip since that may be NULL for cached
1032  * entries that are not present in the current tree.
1033  */
1034 int
1035 e_devid_cache_path_to_devid(char *path, char *ua,
1036     char *nodenamebuf, ddi_devid_t *devidp)
1037 {
1038 	size_t pathlen, ualen;
1039 	int rv = DDI_FAILURE;
1040 	nvp_devid_t *np;
1041 	list_t *listp;
1042 	char *cand;
1043 
1044 	if (path == NULL || *path == '\0' || (ua && *ua == '\0') ||
1045 	    devidp == NULL)
1046 		return (DDI_FAILURE);
1047 
1048 	*devidp = NULL;
1049 
1050 	if (ua) {
1051 		pathlen = strlen(path);
1052 		ualen = strlen(ua);
1053 	}
1054 
1055 	rw_enter(nvf_lock(dcfd_handle), RW_READER);
1056 
1057 	listp = nvf_list(dcfd_handle);
1058 	for (np = list_head(listp); np; np = list_next(listp, np)) {
1059 		size_t nodelen, candlen, n;
1060 		ddi_devid_t devid_dup;
1061 		char *uasep, *node;
1062 
1063 		if (np->nvp_devid == NULL)
1064 			continue;
1065 
1066 		if (ddi_devid_valid(np->nvp_devid) != DDI_SUCCESS) {
1067 			DEVIDERR((CE_CONT,
1068 			    "pathsearch: invalid devid %s\n",
1069 			    np->nvp_devpath));
1070 			continue;
1071 		}
1072 
1073 		cand = np->nvp_devpath;		/* candidate path */
1074 
1075 		/* If a full pathname was provided the compare is easy */
1076 		if (ua == NULL) {
1077 			if (strcmp(cand, path) == 0)
1078 				goto match;
1079 			else
1080 				continue;
1081 		}
1082 
1083 		/*
1084 		 * The compare for initial path plus ua and unknown nodename
1085 		 * is trickier.
1086 		 *
1087 		 * Does the initial path component match 'path'?
1088 		 */
1089 		if (strncmp(path, cand, pathlen) != 0)
1090 			continue;
1091 
1092 		candlen = strlen(cand);
1093 
1094 		/*
1095 		 * The next character must be a '/' and there must be no
1096 		 * further '/' thereafter.  Begin by checking that the
1097 		 * candidate is long enough to include at mininum a
1098 		 * "/<nodename>@<ua>" after the initial portion already
1099 		 * matched assuming a nodename length of 1.
1100 		 */
1101 		if (candlen < pathlen + 1 + 1 + 1 + ualen ||
1102 		    cand[pathlen] != '/' ||
1103 		    strchr(cand + pathlen + 1, '/') != NULL)
1104 			continue;
1105 
1106 		node = cand + pathlen + 1;	/* <node>@<ua> string */
1107 
1108 		/*
1109 		 * Find the '@' before the unit address.  Check for
1110 		 * unit address match.
1111 		 */
1112 		if ((uasep = strchr(node, '@')) == NULL)
1113 			continue;
1114 
1115 		/*
1116 		 * Check we still have enough length and that ua matches
1117 		 */
1118 		nodelen = (uintptr_t)uasep - (uintptr_t)node;
1119 		if (candlen < pathlen + 1 + nodelen + 1 + ualen ||
1120 		    strncmp(ua, uasep + 1, ualen) != 0)
1121 			continue;
1122 match:
1123 		n = ddi_devid_sizeof(np->nvp_devid);
1124 		devid_dup = kmem_alloc(n, KM_SLEEP);	/* caller must free */
1125 		(void) bcopy(np->nvp_devid, devid_dup, n);
1126 		*devidp = devid_dup;
1127 
1128 		if (ua && nodenamebuf) {
1129 			(void) strncpy(nodenamebuf, node, nodelen);
1130 			nodenamebuf[nodelen] = '\0';
1131 		}
1132 
1133 		rv = DDI_SUCCESS;
1134 		break;
1135 	}
1136 
1137 	rw_exit(nvf_lock(dcfd_handle));
1138 
1139 	return (rv);
1140 }
1141 
1142 #ifdef	DEBUG
1143 static void
1144 devid_log(char *fmt, ddi_devid_t devid, char *path)
1145 {
1146 	char *devidstr = ddi_devid_str_encode(devid, NULL);
1147 	if (path) {
1148 		cmn_err(CE_CONT, "%s: %s %s\n", fmt, path, devidstr);
1149 	} else {
1150 		cmn_err(CE_CONT, "%s: %s\n", fmt, devidstr);
1151 	}
1152 	ddi_devid_str_free(devidstr);
1153 }
1154 #endif	/* DEBUG */
1155