xref: /titanic_44/usr/src/uts/common/fs/devfs/devfs_subr.c (revision 30a5e8fa1253cb33980ee4514743cf683f584b4e)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * miscellaneous routines for the devfs
30  */
31 
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/t_lock.h>
35 #include <sys/systm.h>
36 #include <sys/sysmacros.h>
37 #include <sys/user.h>
38 #include <sys/time.h>
39 #include <sys/vfs.h>
40 #include <sys/vnode.h>
41 #include <sys/file.h>
42 #include <sys/fcntl.h>
43 #include <sys/flock.h>
44 #include <sys/kmem.h>
45 #include <sys/uio.h>
46 #include <sys/errno.h>
47 #include <sys/stat.h>
48 #include <sys/cred.h>
49 #include <sys/dirent.h>
50 #include <sys/pathname.h>
51 #include <sys/cmn_err.h>
52 #include <sys/debug.h>
53 #include <sys/modctl.h>
54 #include <fs/fs_subr.h>
55 #include <sys/fs/dv_node.h>
56 #include <sys/fs/snode.h>
57 #include <sys/sunndi.h>
58 #include <sys/sunmdi.h>
59 #include <sys/conf.h>
60 
61 #ifdef DEBUG
62 int devfs_debug = 0x0;
63 #endif
64 
65 const char	dvnm[] = "devfs";
66 kmem_cache_t	*dv_node_cache;	/* dv_node cache */
67 
68 /*
69  * The devfs_clean_key is taken during a devfs_clean operation: it is used to
70  * prevent unnecessary code execution and for detection of potential deadlocks.
71  */
72 uint_t		devfs_clean_key;
73 
74 struct dv_node *dvroot;
75 
76 /* prototype memory vattrs */
77 vattr_t dv_vattr_dir = {
78 	AT_TYPE|AT_MODE|AT_UID|AT_GID, 		/* va_mask */
79 	VDIR,					/* va_type */
80 	DV_DIRMODE_DEFAULT,			/* va_mode */
81 	DV_UID_DEFAULT,				/* va_uid */
82 	DV_GID_DEFAULT,				/* va_gid */
83 	0,					/* va_fsid; */
84 	0,					/* va_nodeid; */
85 	0,					/* va_nlink; */
86 	0,					/* va_size; */
87 	0,					/* va_atime; */
88 	0,					/* va_mtime; */
89 	0,					/* va_ctime; */
90 	0,					/* va_rdev; */
91 	0,					/* va_blksize; */
92 	0,					/* va_nblocks; */
93 	0,					/* va_seq; */
94 };
95 
96 vattr_t dv_vattr_file = {
97 	AT_TYPE|AT_MODE|AT_SIZE|AT_UID|AT_GID|AT_RDEV,	/* va_mask */
98 	0,					/* va_type */
99 	DV_DEVMODE_DEFAULT,			/* va_mode */
100 	DV_UID_DEFAULT,				/* va_uid */
101 	DV_GID_DEFAULT,				/* va_gid */
102 	0,					/* va_fsid; */
103 	0,					/* va_nodeid; */
104 	0,					/* va_nlink; */
105 	0,					/* va_size; */
106 	0,					/* va_atime; */
107 	0,					/* va_mtime; */
108 	0,					/* va_ctime; */
109 	0,					/* va_rdev; */
110 	0,					/* va_blksize; */
111 	0,					/* va_nblocks; */
112 	0,					/* va_seq; */
113 };
114 
115 vattr_t dv_vattr_priv = {
116 	AT_TYPE|AT_MODE|AT_SIZE|AT_UID|AT_GID|AT_RDEV,	/* va_mask */
117 	0,					/* va_type */
118 	DV_DEVMODE_PRIV,			/* va_mode */
119 	DV_UID_DEFAULT,				/* va_uid */
120 	DV_GID_DEFAULT,				/* va_gid */
121 	0,					/* va_fsid; */
122 	0,					/* va_nodeid; */
123 	0,					/* va_nlink; */
124 	0,					/* va_size; */
125 	0,					/* va_atime; */
126 	0,					/* va_mtime; */
127 	0,					/* va_ctime; */
128 	0,					/* va_rdev; */
129 	0,					/* va_blksize; */
130 	0,					/* va_nblocks; */
131 	0,					/* va_seq; */
132 };
133 
134 extern dev_info_t	*clone_dip;
135 extern major_t		clone_major;
136 extern struct dev_ops	*ddi_hold_driver(major_t);
137 
138 /*
139  * dv_node cache constructor, destructor, can cache creation
140  */
141 /*ARGSUSED1*/
142 static int
143 i_dv_node_ctor(void *buf, void *cfarg, int flag)
144 {
145 	struct dv_node	*dv = (struct dv_node *)buf;
146 	struct vnode	*vp;
147 
148 	bzero(buf, sizeof (struct dv_node));
149 
150 	/* initialize persistent parts of dv_node */
151 	rw_init(&dv->dv_contents, NULL, RW_DEFAULT, NULL);
152 
153 	/* allocate vnode and initialize link back to dv_node */
154 	dv->dv_vnode = vn_alloc(KM_SLEEP);
155 	vp = DVTOV(dv);
156 	vp->v_data = (caddr_t)dv;
157 	return (0);
158 }
159 
160 /* dev_info node destructor for kmem cache */
161 /*ARGSUSED1*/
162 static void
163 i_dv_node_dtor(void *buf, void *arg)
164 {
165 	struct dv_node	*dv = (struct dv_node *)buf;
166 	struct vnode	*vp = DVTOV(dv);
167 
168 	rw_destroy(&dv->dv_contents);
169 	vn_invalid(vp);
170 	vn_free(vp);
171 }
172 
173 
174 /* initialize dev_info node cache */
175 void
176 dv_node_cache_init()
177 {
178 	ASSERT(dv_node_cache == NULL);
179 	dv_node_cache = kmem_cache_create("dv_node_cache",
180 	    sizeof (struct dv_node), 0, i_dv_node_ctor, i_dv_node_dtor,
181 	    NULL, NULL, NULL, 0);
182 
183 	tsd_create(&devfs_clean_key, NULL);
184 }
185 
186 /* initialize dev_info node cache */
187 void
188 dv_node_cache_fini()
189 {
190 	ASSERT(dv_node_cache != NULL);
191 	kmem_cache_destroy(dv_node_cache);
192 	dv_node_cache = NULL;
193 
194 	tsd_destroy(&devfs_clean_key);
195 }
196 
197 /*
198  * dv_mkino - Generate a unique inode number for devfs nodes.
199  *
200  * Although ino_t is 64 bits, the inode number is truncated to 32 bits for 32
201  * bit non-LARGEFILE applications. This means that there is a requirement to
202  * maintain the inode number as a 32 bit value or applications will have
203  * stat(2) calls fail with EOVERFLOW.  We form a 32 bit inode number from the
204  * dev_t. but if the minor number is larger than L_MAXMIN32 we fold extra minor
205  *
206  * To generate inode numbers for directories, we assume that we will never use
207  * more than half the major space - this allows for ~8190 drivers. We use this
208  * upper major number space to allocate inode numbers for directories by
209  * encoding the major and instance into this space.
210  *
211  * We also skew the result so that inode 2 is reserved for the root of the file
212  * system.
213  *
214  * As part of the future support for 64-bit dev_t APIs, the upper minor bits
215  * should be folded into the high inode bits by adding the following code
216  * after "ino |= 1":
217  *
218  * #if (L_BITSMINOR32 != L_BITSMINOR)
219  *		|* fold overflow minor bits into high bits of inode number *|
220  *		ino |= ((ino_t)(minor >> L_BITSMINOR32)) << L_BITSMINOR;
221  * #endif |* (L_BITSMINOR32 != L_BITSMINOR) *|
222  *
223  * This way only applications that use devices that overflow their minor
224  * space will have an application level impact.
225  */
226 static ino_t
227 dv_mkino(dev_info_t *devi, vtype_t typ, dev_t dev)
228 {
229 	major_t		major;
230 	minor_t		minor;
231 	ino_t		ino;
232 	static int	warn;
233 
234 	if (typ == VDIR) {
235 		major = ((L_MAXMAJ32 + 1) >> 1) + DEVI(devi)->devi_major;
236 		minor = ddi_get_instance(devi);
237 
238 		/* makedevice32 in high half of major number space */
239 		ino = (ino_t)((major << L_BITSMINOR32) | (minor & L_MAXMIN32));
240 
241 		major = DEVI(devi)->devi_major;
242 	} else {
243 		major = getmajor(dev);
244 		minor = getminor(dev);
245 
246 		/* makedevice32 */
247 		ino = (ino_t)((major << L_BITSMINOR32) | (minor & L_MAXMIN32));
248 
249 		/* make ino for VCHR different than VBLK */
250 		ino <<= 1;
251 		if (typ == VCHR)
252 			ino |= 1;
253 	}
254 
255 	ino += DV_ROOTINO + 1;		/* skew */
256 
257 	/*
258 	 * diagnose things a little early because adding the skew to a large
259 	 * minor number could roll over the major.
260 	 */
261 	if ((major >= (L_MAXMAJ32 >> 1)) && (warn == 0)) {
262 		warn = 1;
263 		cmn_err(CE_WARN, "%s: inode numbers are not unique", dvnm);
264 	}
265 
266 	return (ino);
267 }
268 
269 /*
270  * dv_mkroot
271  *
272  * Build the first VDIR dv_node.
273  */
274 struct dv_node *
275 dv_mkroot(struct vfs *vfsp, dev_t devfsdev)
276 {
277 	struct dv_node *dv;
278 	struct vnode *vp;
279 
280 	ASSERT(ddi_root_node() != NULL);
281 	ASSERT(dv_node_cache != NULL);
282 
283 	dcmn_err3(("dv_mkroot\n"));
284 	dv = kmem_cache_alloc(dv_node_cache, KM_SLEEP);
285 	vp = DVTOV(dv);
286 	vn_reinit(vp);
287 	vp->v_flag = VROOT;
288 	vp->v_vfsp = vfsp;
289 	vp->v_type = VDIR;
290 	vp->v_rdev = devfsdev;
291 	vn_setops(vp, dv_vnodeops);
292 	vn_exists(vp);
293 
294 	dvroot = dv;
295 
296 	dv->dv_name = NULL;		/* not needed */
297 	dv->dv_namelen = 0;
298 
299 	dv->dv_devi = ddi_root_node();
300 
301 	dv->dv_ino = DV_ROOTINO;
302 	dv->dv_nlink = 2;		/* name + . (no dv_insert) */
303 	dv->dv_dotdot = dv;		/* .. == self */
304 	dv->dv_attrvp = NULLVP;
305 	dv->dv_attr = NULL;
306 	dv->dv_flags = DV_BUILD;
307 	dv->dv_priv = NULL;
308 	dv->dv_busy = 0;
309 	dv->dv_dflt_mode = 0;
310 
311 	return (dv);
312 }
313 
314 /*
315  * dv_mkdir
316  *
317  * Given an probed or attached nexus node, create a VDIR dv_node.
318  * No dv_attrvp is created at this point.
319  */
320 struct dv_node *
321 dv_mkdir(struct dv_node *ddv, dev_info_t *devi, char *nm)
322 {
323 	struct dv_node *dv;
324 	struct vnode *vp;
325 	size_t nmlen;
326 
327 	ASSERT((devi));
328 	dcmn_err4(("dv_mkdir: %s\n", nm));
329 
330 	dv = kmem_cache_alloc(dv_node_cache, KM_SLEEP);
331 	nmlen = strlen(nm) + 1;
332 	dv->dv_name = kmem_alloc(nmlen, KM_SLEEP);
333 	bcopy(nm, dv->dv_name, nmlen);
334 	dv->dv_namelen = nmlen - 1;	/* '\0' not included */
335 	vp = DVTOV(dv);
336 	vn_reinit(vp);
337 	vp->v_flag = 0;
338 	vp->v_vfsp = DVTOV(ddv)->v_vfsp;
339 	vp->v_type = VDIR;
340 	vp->v_rdev = DVTOV(ddv)->v_rdev;
341 	vn_setops(vp, vn_getops(DVTOV(ddv)));
342 	vn_exists(vp);
343 
344 	dv->dv_devi = devi;
345 	ndi_hold_devi(devi);
346 
347 	dv->dv_ino = dv_mkino(devi, VDIR, NODEV);
348 	dv->dv_nlink = 0;		/* updated on insert */
349 	dv->dv_dotdot = ddv;
350 	dv->dv_attrvp = NULLVP;
351 	dv->dv_attr = NULL;
352 	dv->dv_flags = DV_BUILD;
353 	dv->dv_priv = NULL;
354 	dv->dv_busy = 0;
355 	dv->dv_dflt_mode = 0;
356 
357 	return (dv);
358 }
359 
360 /*
361  * dv_mknod
362  *
363  * Given a minor node, create a VCHR or VBLK dv_node.
364  * No dv_attrvp is created at this point.
365  */
366 static struct dv_node *
367 dv_mknod(struct dv_node *ddv, dev_info_t *devi, char *nm,
368 	struct ddi_minor_data *dmd)
369 {
370 	struct dv_node *dv;
371 	struct vnode *vp;
372 	size_t nmlen;
373 
374 	dcmn_err4(("dv_mknod: %s\n", nm));
375 
376 	dv = kmem_cache_alloc(dv_node_cache, KM_SLEEP);
377 	nmlen = strlen(nm) + 1;
378 	dv->dv_name = kmem_alloc(nmlen, KM_SLEEP);
379 	bcopy(nm, dv->dv_name, nmlen);
380 	dv->dv_namelen = nmlen - 1;	/* no '\0' */
381 	vp = DVTOV(dv);
382 	vn_reinit(vp);
383 	vp->v_flag = 0;
384 	vp->v_vfsp = DVTOV(ddv)->v_vfsp;
385 	vp->v_type = dmd->ddm_spec_type == S_IFCHR ? VCHR : VBLK;
386 	vp->v_rdev = dmd->ddm_dev;
387 	vn_setops(vp, vn_getops(DVTOV(ddv)));
388 	vn_exists(vp);
389 
390 	ASSERT(MUTEX_HELD(&DEVI(devi)->devi_lock));
391 	dv->dv_devi = devi;
392 	DEVI(devi)->devi_ref++;
393 
394 	dv->dv_ino = dv_mkino(devi, vp->v_type, vp->v_rdev);
395 	dv->dv_nlink = 0;		/* updated on insert */
396 	dv->dv_dotdot = ddv;
397 	dv->dv_attrvp = NULLVP;
398 	dv->dv_attr = NULL;
399 	dv->dv_flags = 0;
400 
401 	if (dmd->type == DDM_INTERNAL_PATH)
402 		dv->dv_flags |= DV_INTERNAL;
403 	if (dmd->ddm_flags & DM_NO_FSPERM)
404 		dv->dv_flags |= DV_NO_FSPERM;
405 
406 	dv->dv_priv = dmd->ddm_node_priv;
407 	if (dv->dv_priv)
408 		dphold(dv->dv_priv);
409 
410 	/*
411 	 * Minors created with ddi_create_priv_minor_node can specify
412 	 * a default mode permission other than the devfs default.
413 	 */
414 	if (dv->dv_priv || dv->dv_flags & DV_NO_FSPERM) {
415 		dcmn_err5(("%s: dv_mknod default priv mode 0%o\n",
416 		    dv->dv_name, dmd->ddm_priv_mode));
417 		dv->dv_flags |= DV_DFLT_MODE;
418 		dv->dv_dflt_mode = dmd->ddm_priv_mode & S_IAMB;
419 	}
420 
421 	return (dv);
422 }
423 
424 /*
425  * dv_destroy
426  *
427  * Destroy what we created in dv_mkdir or dv_mknod.
428  * In the case of a *referenced* directory, do nothing.
429  */
430 /*ARGSUSED1*/
431 void
432 dv_destroy(struct dv_node *dv, uint_t flags)
433 {
434 	vnode_t *vp = DVTOV(dv);
435 	ASSERT(dv->dv_nlink == 0);		/* no references */
436 	ASSERT(dv->dv_next == NULL);		/* unlinked from directory */
437 
438 	dcmn_err4(("dv_destroy: %s\n", dv->dv_name));
439 
440 	/*
441 	 * We may be asked to unlink referenced directories.
442 	 * In this case, there is nothing to be done.
443 	 * The eventual memory free will be done in
444 	 * devfs_inactive.
445 	 */
446 	if (vp->v_count != 0) {
447 		ASSERT(vp->v_type == VDIR);
448 		ASSERT(flags & DV_CLEAN_FORCE);
449 		ASSERT(DV_STALE(dv));
450 		return;
451 	}
452 
453 	if (dv->dv_attrvp != NULLVP)
454 		VN_RELE(dv->dv_attrvp);
455 	if (dv->dv_attr != NULL)
456 		kmem_free(dv->dv_attr, sizeof (struct vattr));
457 	if (dv->dv_name != NULL)
458 		kmem_free(dv->dv_name, dv->dv_namelen + 1);
459 	if (dv->dv_devi != NULL) {
460 		ndi_rele_devi(dv->dv_devi);
461 	}
462 	if (dv->dv_priv != NULL) {
463 		dpfree(dv->dv_priv);
464 	}
465 
466 	kmem_cache_free(dv_node_cache, dv);
467 }
468 
469 /*
470  * Find and hold dv_node by name
471  */
472 struct dv_node *
473 dv_findbyname(struct dv_node *ddv, char *nm)
474 {
475 	struct dv_node	*dv;
476 	size_t		nmlen = strlen(nm);
477 
478 	ASSERT(RW_LOCK_HELD(&ddv->dv_contents));
479 	dcmn_err3(("dv_findbyname: %s\n", nm));
480 	for (dv = ddv->dv_dot; dv; dv = dv->dv_next) {
481 		if (dv->dv_namelen != nmlen)
482 			continue;
483 		if (strcmp(dv->dv_name, nm) == 0) {
484 			VN_HOLD(DVTOV(dv));
485 			return (dv);
486 		}
487 	}
488 	return (NULL);
489 }
490 
491 /*
492  * Inserts a new dv_node in a parent directory
493  */
494 void
495 dv_insert(struct dv_node *ddv, struct dv_node *dv)
496 {
497 	ASSERT(RW_WRITE_HELD(&ddv->dv_contents));
498 	ASSERT(DVTOV(ddv)->v_type == VDIR);
499 	ASSERT(ddv->dv_nlink >= 2);
500 	ASSERT(dv->dv_nlink == 0);
501 
502 	dcmn_err3(("dv_insert: %s\n", dv->dv_name));
503 
504 	dv->dv_dotdot = ddv;
505 	dv->dv_next = ddv->dv_dot;
506 	ddv->dv_dot = dv;
507 	if (DVTOV(dv)->v_type == VDIR) {
508 		ddv->dv_nlink++;	/* .. to containing directory */
509 		dv->dv_nlink = 2;	/* name + . */
510 	} else {
511 		dv->dv_nlink = 1;	/* name */
512 	}
513 }
514 
515 /*
516  * Unlink a dv_node from a perent directory
517  */
518 void
519 dv_unlink(struct dv_node *ddv, struct dv_node *dv, struct dv_node **dv_pprev)
520 {
521 	/* verify linkage of arguments */
522 	ASSERT(ddv && dv && dv_pprev);
523 	ASSERT(dv->dv_dotdot == ddv);
524 	ASSERT(*dv_pprev == dv);
525 	ASSERT(RW_WRITE_HELD(&ddv->dv_contents));
526 	ASSERT(DVTOV(ddv)->v_type == VDIR);
527 
528 	dcmn_err3(("dv_unlink: %s\n", dv->dv_name));
529 
530 	if (DVTOV(dv)->v_type == VDIR) {
531 		ddv->dv_nlink--;	/* .. to containing directory */
532 		dv->dv_nlink -= 2;	/* name + . */
533 	} else {
534 		dv->dv_nlink -= 1;	/* name */
535 	}
536 	ASSERT(ddv->dv_nlink >= 2);
537 	ASSERT(dv->dv_nlink == 0);
538 
539 	/* update ddv->dv_dot/dv_next */
540 	*dv_pprev = dv->dv_next;
541 
542 	dv->dv_dotdot = NULL;
543 	dv->dv_next = NULL;
544 	dv->dv_dot = NULL;
545 }
546 
547 /*
548  * Merge devfs node specific information into an attribute structure.
549  *
550  * NOTE: specfs provides ATIME,MTIME,CTIME,SIZE,BLKSIZE,NBLOCKS on leaf node.
551  */
552 void
553 dv_vattr_merge(struct dv_node *dv, struct vattr *vap)
554 {
555 	struct vnode *vp = DVTOV(dv);
556 
557 	vap->va_nodeid = dv->dv_ino;
558 	vap->va_nlink = dv->dv_nlink;
559 
560 	if (vp->v_type == VDIR) {
561 		vap->va_rdev = 0;
562 		vap->va_fsid = vp->v_rdev;
563 	} else {
564 		vap->va_rdev = vp->v_rdev;
565 		vap->va_fsid = DVTOV(dv->dv_dotdot)->v_rdev;
566 		vap->va_type = vp->v_type;
567 		/* don't trust the shadow file type */
568 		vap->va_mode &= ~S_IFMT;
569 		if (vap->va_type == VCHR)
570 			vap->va_mode |= S_IFCHR;
571 		else
572 			vap->va_mode |= S_IFBLK;
573 	}
574 }
575 
576 /*
577  * Get default device permission by consulting rules in
578  * privilege specification in minor node and /etc/minor_perm.
579  *
580  * This function is called from the devname filesystem to get default
581  * permissions for a device exported to a non-global zone.
582  */
583 void
584 devfs_get_defattr(struct vnode *vp, struct vattr *vap, int *no_fs_perm)
585 {
586 	mperm_t	mp;
587 	struct dv_node *dv;
588 
589 	/* If vp isn't a dv_node, return something sensible */
590 	if (!vn_matchops(vp, dv_vnodeops)) {
591 		if (no_fs_perm)
592 			*no_fs_perm = 0;
593 		*vap = dv_vattr_file;
594 		return;
595 	}
596 
597 	/*
598 	 * For minors not created by ddi_create_priv_minor_node(),
599 	 * use devfs defaults.
600 	 */
601 	dv = VTODV(vp);
602 	if (vp->v_type == VDIR) {
603 		*vap = dv_vattr_dir;
604 	} else if (dv->dv_flags & DV_NO_FSPERM) {
605 		if (no_fs_perm)
606 			*no_fs_perm = 1;
607 		*vap = dv_vattr_priv;
608 	} else {
609 		/*
610 		 * look up perm bits from minor_perm
611 		 */
612 		*vap = dv_vattr_file;
613 		if (dev_minorperm(dv->dv_devi, dv->dv_name, &mp) == 0) {
614 			VATTR_MP_MERGE((*vap), mp);
615 			dcmn_err5(("%s: minor perm mode 0%o\n",
616 			    dv->dv_name, vap->va_mode));
617 		} else if (dv->dv_flags & DV_DFLT_MODE) {
618 			ASSERT((dv->dv_dflt_mode & ~S_IAMB) == 0);
619 			vap->va_mode &= ~S_IAMB;
620 			vap->va_mode |= dv->dv_dflt_mode;
621 			dcmn_err5(("%s: priv mode 0%o\n",
622 			    dv->dv_name, vap->va_mode));
623 		}
624 	}
625 }
626 
627 /*
628  * dv_shadow_node
629  *
630  * Given a VDIR dv_node, find/create the associated VDIR
631  * node in the shadow attribute filesystem.
632  *
633  * Given a VCHR/VBLK dv_node, find the associated VREG
634  * node in the shadow attribute filesystem.  These nodes
635  * are only created to persist non-default attributes.
636  * Lack of such a node implies the default permissions
637  * are sufficient.
638  *
639  * Managing the attribute file entries is slightly tricky (mostly
640  * because we can't intercept VN_HOLD and VN_RELE except on the last
641  * release).
642  *
643  * We assert that if the dv_attrvp pointer is non-NULL, it points
644  * to a singly-held (by us) vnode that represents the shadow entry
645  * in the underlying filesystem.  To avoid store-ordering issues,
646  * we assert that the pointer can only be tested under the dv_contents
647  * READERS lock.
648  */
649 
650 void
651 dv_shadow_node(
652 	struct vnode *dvp,	/* devfs parent directory vnode */
653 	char *nm,		/* name component */
654 	struct vnode *vp,	/* devfs vnode */
655 	struct pathname *pnp,	/* the path .. */
656 	struct vnode *rdir,	/* the root .. */
657 	struct cred *cred,	/* who's asking? */
658 	int flags)		/* optionally create shadow node */
659 {
660 	struct dv_node	*dv;	/* dv_node of named directory */
661 	struct vnode	*rdvp;	/* shadow parent directory vnode */
662 	struct vnode	*rvp;	/* shadow vnode */
663 	struct vnode	*rrvp;	/* realvp of shadow vnode */
664 	struct vattr	vattr;
665 	int		create_tried;
666 	int		error;
667 
668 	ASSERT(vp->v_type == VDIR || vp->v_type == VCHR || vp->v_type == VBLK);
669 	dv = VTODV(vp);
670 	dcmn_err3(("dv_shadow_node: name %s attr %p\n",
671 	    nm, (void *)dv->dv_attrvp));
672 
673 	if ((flags & DV_SHADOW_WRITE_HELD) == 0) {
674 		ASSERT(RW_READ_HELD(&dv->dv_contents));
675 		if (dv->dv_attrvp != NULLVP)
676 			return;
677 		if (!rw_tryupgrade(&dv->dv_contents)) {
678 			rw_exit(&dv->dv_contents);
679 			rw_enter(&dv->dv_contents, RW_WRITER);
680 			if (dv->dv_attrvp != NULLVP) {
681 				rw_downgrade(&dv->dv_contents);
682 				return;
683 			}
684 		}
685 	} else {
686 		ASSERT(RW_WRITE_HELD(&dv->dv_contents));
687 		if (dv->dv_attrvp != NULLVP)
688 			return;
689 	}
690 
691 	ASSERT(RW_WRITE_HELD(&dv->dv_contents) && dv->dv_attrvp == NULL);
692 
693 	rdvp = VTODV(dvp)->dv_attrvp;
694 	create_tried = 0;
695 lookup:
696 	if (rdvp && (dv->dv_flags & DV_NO_FSPERM) == 0) {
697 		error = VOP_LOOKUP(rdvp, nm, &rvp, pnp, LOOKUP_DIR, rdir, cred);
698 
699 		/* factor out the snode since we only want the attribute node */
700 		if ((error == 0) && (VOP_REALVP(rvp, &rrvp) == 0)) {
701 			VN_HOLD(rrvp);
702 			VN_RELE(rvp);
703 			rvp = rrvp;
704 		}
705 	} else
706 		error = EROFS;		/* no parent, no entry */
707 
708 	/*
709 	 * All we want is the permissions (and maybe ACLs and
710 	 * extended attributes), and we want to perform lookups
711 	 * by name.  Drivers occasionally change their minor
712 	 * number space.  If something changes, there's no
713 	 * much we can do about it here.
714 	 */
715 
716 	/* The shadow node checks out. We are done */
717 	if (error == 0) {
718 		dv->dv_attrvp = rvp;	/* with one hold */
719 
720 		/*
721 		 * Determine if we have non-trivial ACLs on this node.
722 		 * It is not necessary to VOP_RWLOCK since fs_acl_nontrivial
723 		 * only does VOP_GETSECATTR.
724 		 */
725 		dv->dv_flags &= ~DV_ACL;
726 
727 		if (fs_acl_nontrivial(rvp, cred))
728 			dv->dv_flags |= DV_ACL;
729 
730 		/*
731 		 * If we have synced out the memory attributes, free
732 		 * them and switch back to using the persistent store.
733 		 */
734 		if (rvp && dv->dv_attr) {
735 			kmem_free(dv->dv_attr, sizeof (struct vattr));
736 			dv->dv_attr = NULL;
737 		}
738 		if ((flags & DV_SHADOW_WRITE_HELD) == 0)
739 			rw_downgrade(&dv->dv_contents);
740 		ASSERT(RW_LOCK_HELD(&dv->dv_contents));
741 		return;
742 	}
743 
744 	/*
745 	 * Failed to find attribute in persistent backing store,
746 	 * get default permission bits.
747 	 */
748 	devfs_get_defattr(vp, &vattr, NULL);
749 
750 	dv_vattr_merge(dv, &vattr);
751 	gethrestime(&vattr.va_atime);
752 	vattr.va_mtime = vattr.va_atime;
753 	vattr.va_ctime = vattr.va_atime;
754 
755 	/*
756 	 * Try to create shadow dir. This is necessary in case
757 	 * we need to create a shadow leaf node later, when user
758 	 * executes chmod.
759 	 */
760 	if ((error == ENOENT) && !create_tried) {
761 		switch (vp->v_type) {
762 		case VDIR:
763 			error = VOP_MKDIR(rdvp, nm, &vattr, &rvp, kcred);
764 			dsysdebug(error, ("vop_mkdir %s %s %d\n",
765 			    VTODV(dvp)->dv_name, nm, error));
766 			create_tried = 1;
767 			break;
768 
769 		case VCHR:
770 		case VBLK:
771 			/*
772 			 * Shadow nodes are only created on demand
773 			 */
774 			if (flags & DV_SHADOW_CREATE) {
775 				error = VOP_CREATE(rdvp, nm, &vattr, NONEXCL,
776 				    VREAD|VWRITE, &rvp, kcred, 0);
777 				dsysdebug(error, ("vop_create %s %s %d\n",
778 				    VTODV(dvp)->dv_name, nm, error));
779 				create_tried = 1;
780 			}
781 			break;
782 
783 		default:
784 			cmn_err(CE_PANIC, "devfs: %s: create", dvnm);
785 			/*NOTREACHED*/
786 		}
787 
788 		if (create_tried &&
789 		    (error == 0) || (error == EEXIST)) {
790 			VN_RELE(rvp);
791 			goto lookup;
792 		}
793 	}
794 
795 	/* Store attribute in memory */
796 	if (dv->dv_attr == NULL) {
797 		dv->dv_attr = kmem_alloc(sizeof (struct vattr), KM_SLEEP);
798 		*(dv->dv_attr) = vattr;
799 	}
800 
801 	if ((flags & DV_SHADOW_WRITE_HELD) == 0)
802 		rw_downgrade(&dv->dv_contents);
803 	ASSERT(RW_LOCK_HELD(&dv->dv_contents));
804 }
805 
806 /*
807  * Given a devinfo node, and a name, returns the appropriate
808  * minor information for that named node, if it exists.
809  */
810 static int
811 dv_find_leafnode(dev_info_t *devi, char *minor_nm, struct ddi_minor_data *r_mi)
812 {
813 	struct ddi_minor_data *dmd;
814 
815 	ASSERT(i_ddi_devi_attached(devi));
816 	ASSERT(MUTEX_HELD(&DEVI(devi)->devi_lock));
817 
818 	dcmn_err3(("dv_find_leafnode: %s\n", minor_nm));
819 	for (dmd = DEVI(devi)->devi_minor; dmd; dmd = dmd->next) {
820 
821 		/*
822 		 * Skip alias nodes and nodes without a name.
823 		 */
824 		if ((dmd->type == DDM_ALIAS) || (dmd->ddm_name == NULL))
825 			    continue;
826 
827 		dcmn_err4(("dv_find_leafnode: (%s,%s)\n",
828 			minor_nm, dmd->ddm_name));
829 		if (strcmp(minor_nm, dmd->ddm_name) == 0) {
830 			r_mi->ddm_dev = dmd->ddm_dev;
831 			r_mi->ddm_spec_type = dmd->ddm_spec_type;
832 			r_mi->type = dmd->type;
833 			r_mi->ddm_flags = dmd->ddm_flags;
834 			r_mi->ddm_node_priv = dmd->ddm_node_priv;
835 			r_mi->ddm_priv_mode = dmd->ddm_priv_mode;
836 			if (r_mi->ddm_node_priv)
837 				dphold(r_mi->ddm_node_priv);
838 			return (0);
839 		}
840 	}
841 
842 	dcmn_err3(("dv_find_leafnode: %s: ENOENT\n", minor_nm));
843 	return (ENOENT);
844 }
845 
846 /*
847  * Special handling for clone node:
848  *	Clone minor name is a driver name, the minor number will
849  *	be the major number of the driver. There is no minor
850  *	node under the clone driver, so we'll manufacture the
851  *	dev_t.
852  */
853 static struct dv_node *
854 dv_clone_mknod(struct dv_node *ddv, char *drvname)
855 {
856 	major_t	major;
857 	struct dv_node *dvp;
858 	char *devnm;
859 	struct ddi_minor_data *dmd;
860 
861 	/*
862 	 * Make sure drvname is a STREAMS driver. We load the driver,
863 	 * but don't attach to any instances. This makes stat(2)
864 	 * relatively cheap.
865 	 */
866 	major = ddi_name_to_major(drvname);
867 	if (major == (major_t)-1)
868 		return (NULL);
869 
870 	if (ddi_hold_driver(major) == NULL)
871 		return (NULL);
872 
873 	if (STREAMSTAB(major) == NULL) {
874 		ddi_rele_driver(major);
875 		return (NULL);
876 	}
877 
878 	ddi_rele_driver(major);
879 	devnm = kmem_alloc(MAXNAMELEN, KM_SLEEP);
880 	(void) snprintf(devnm, MAXNAMELEN, "clone@0:%s", drvname);
881 	dmd = kmem_zalloc(sizeof (*dmd), KM_SLEEP);
882 	dmd->ddm_dev = makedevice(clone_major, (minor_t)major);
883 	dmd->ddm_spec_type = S_IFCHR;
884 	dvp = dv_mknod(ddv, clone_dip, devnm, dmd);
885 	kmem_free(dmd, sizeof (*dmd));
886 	kmem_free(devnm, MAXNAMELEN);
887 	return (dvp);
888 }
889 
890 /*
891  * Given the parent directory node, and a name in it, returns the
892  * named dv_node to the caller (as a vnode).
893  *
894  * (We need pnp and rdir for doing shadow lookups; they can be NULL)
895  */
896 int
897 dv_find(struct dv_node *ddv, char *nm, struct vnode **vpp, struct pathname *pnp,
898 	struct vnode *rdir, struct cred *cred, uint_t ndi_flags)
899 {
900 	extern int isminiroot;	/* see modctl.c */
901 
902 	int rv = 0, was_busy = 0, nmlen, write_held = 0;
903 	struct vnode *vp;
904 	struct dv_node *dv, *dup;
905 	dev_info_t *pdevi, *devi = NULL;
906 	char *mnm;
907 	struct ddi_minor_data *dmd;
908 
909 	dcmn_err3(("dv_find %s\n", nm));
910 
911 	rw_enter(&ddv->dv_contents, RW_READER);
912 start:
913 	if (DV_STALE(ddv)) {
914 		rw_exit(&ddv->dv_contents);
915 		return (ESTALE);
916 	}
917 
918 	/*
919 	 * Empty name or ., return node itself.
920 	 */
921 	nmlen = strlen(nm);
922 	if ((nmlen == 0) || ((nmlen == 1) && (nm[0] == '.'))) {
923 		*vpp = DVTOV(ddv);
924 		rw_exit(&ddv->dv_contents);
925 		VN_HOLD(*vpp);
926 		return (0);
927 	}
928 
929 	/*
930 	 * .., return the parent directory
931 	 */
932 	if ((nmlen == 2) && (strcmp(nm, "..") == 0)) {
933 		*vpp = DVTOV(ddv->dv_dotdot);
934 		rw_exit(&ddv->dv_contents);
935 		VN_HOLD(*vpp);
936 		return (0);
937 	}
938 
939 	/*
940 	 * Fail anything without a valid device name component
941 	 */
942 	if (nm[0] == '@' || nm[0] == ':') {
943 		dcmn_err3(("devfs: no driver '%s'\n", nm));
944 		rw_exit(&ddv->dv_contents);
945 		return (ENOENT);
946 	}
947 
948 	/*
949 	 * So, now we have to deal with the trickier stuff.
950 	 *
951 	 * (a) search the existing list of dv_nodes on this directory
952 	 */
953 	if ((dv = dv_findbyname(ddv, nm)) != NULL) {
954 founddv:
955 		ASSERT(RW_LOCK_HELD(&ddv->dv_contents));
956 
957 		if (!rw_tryenter(&dv->dv_contents, RW_READER)) {
958 			if (tsd_get(devfs_clean_key)) {
959 				VN_RELE(DVTOV(dv));
960 				rw_exit(&ddv->dv_contents);
961 				return (EBUSY);
962 			}
963 			rw_enter(&dv->dv_contents, RW_READER);
964 		}
965 
966 		vp = DVTOV(dv);
967 		if ((dv->dv_attrvp != NULLVP) ||
968 		    (vp->v_type != VDIR && dv->dv_attr != NULL)) {
969 			/*
970 			 * Common case - we already have attributes
971 			 */
972 			rw_exit(&dv->dv_contents);
973 			rw_exit(&ddv->dv_contents);
974 			goto found;
975 		}
976 
977 		/*
978 		 * No attribute vp, try and build one.
979 		 *
980 		 * dv_shadow_node() can briefly drop &dv->dv_contents lock
981 		 * if it is unable to upgrade it to a write lock. If the
982 		 * current thread has come in through the bottom-up device
983 		 * configuration devfs_clean() path, we may deadlock against
984 		 * a thread performing top-down device configuration if it
985 		 * grabs the contents lock. To avoid this, when we are on the
986 		 * devfs_clean() path we attempt to upgrade the dv_contents
987 		 * lock before we call dv_shadow_node().
988 		 */
989 		if (tsd_get(devfs_clean_key)) {
990 			if (!rw_tryupgrade(&dv->dv_contents)) {
991 				VN_RELE(DVTOV(dv));
992 				rw_exit(&dv->dv_contents);
993 				rw_exit(&ddv->dv_contents);
994 				return (EBUSY);
995 			}
996 
997 			write_held = DV_SHADOW_WRITE_HELD;
998 		}
999 
1000 		dv_shadow_node(DVTOV(ddv), nm, vp, pnp, rdir, cred,
1001 		    write_held);
1002 
1003 		rw_exit(&dv->dv_contents);
1004 		rw_exit(&ddv->dv_contents);
1005 		goto found;
1006 	}
1007 
1008 	/*
1009 	 * (b) Search the child devinfo nodes of our parent directory,
1010 	 * looking for the named node.  If we find it, build a new
1011 	 * node, then grab the writers lock, search the directory
1012 	 * if it's still not there, then insert it.
1013 	 *
1014 	 * We drop the devfs locks before accessing the device tree.
1015 	 * Take care to mark the node BUSY so that a forced devfs_clean
1016 	 * doesn't mark the directory node stale.
1017 	 *
1018 	 * Also, check if we are called as part of devfs_clean or
1019 	 * reset_perm. If so, simply return not found because there
1020 	 * is nothing to clean.
1021 	 */
1022 	if (tsd_get(devfs_clean_key)) {
1023 		rw_exit(&ddv->dv_contents);
1024 		return (ENOENT);
1025 	}
1026 
1027 	/*
1028 	 * We could be either READ or WRITE locked at
1029 	 * this point. Upgrade if we are read locked.
1030 	 */
1031 	ASSERT(RW_LOCK_HELD(&ddv->dv_contents));
1032 	if (rw_read_locked(&ddv->dv_contents) &&
1033 	    !rw_tryupgrade(&ddv->dv_contents)) {
1034 		rw_exit(&ddv->dv_contents);
1035 		rw_enter(&ddv->dv_contents, RW_WRITER);
1036 		/*
1037 		 * Things may have changed when we dropped
1038 		 * the contents lock, so start from top again
1039 		 */
1040 		goto start;
1041 	}
1042 	ddv->dv_busy++;		/* mark busy before dropping lock */
1043 	was_busy++;
1044 	rw_exit(&ddv->dv_contents);
1045 
1046 	pdevi = ddv->dv_devi;
1047 	ASSERT(pdevi != NULL);
1048 
1049 	mnm = strchr(nm, ':');
1050 	if (mnm)
1051 		*mnm = (char)0;
1052 
1053 	/*
1054 	 * Configure one nexus child, will call nexus's bus_ops
1055 	 * If successful, devi is held upon returning.
1056 	 * Note: devfs lookup should not be configuring grandchildren.
1057 	 */
1058 	ASSERT((ndi_flags & NDI_CONFIG) == 0);
1059 
1060 	rv = ndi_devi_config_one(pdevi, nm, &devi, ndi_flags | NDI_NO_EVENT);
1061 	if (mnm)
1062 		*mnm = ':';
1063 	if (rv != NDI_SUCCESS) {
1064 		rv = ENOENT;
1065 		goto notfound;
1066 	}
1067 
1068 	/*
1069 	 * Don't make vhci clients visible under phci, unless we
1070 	 * are in miniroot.
1071 	 */
1072 	if (isminiroot == 0 && ddi_get_parent(devi) != pdevi) {
1073 		ndi_rele_devi(devi);
1074 		rv = ENOENT;
1075 		goto notfound;
1076 	}
1077 
1078 	ASSERT(devi && i_ddi_devi_attached(devi));
1079 
1080 	/*
1081 	 * Invalidate cache to notice newly created minor nodes.
1082 	 */
1083 	rw_enter(&ddv->dv_contents, RW_WRITER);
1084 	ddv->dv_flags |= DV_BUILD;
1085 	rw_exit(&ddv->dv_contents);
1086 
1087 	/*
1088 	 * mkdir for nexus drivers and leaf nodes as well.  If we are racing
1089 	 * and create a duplicate, the duplicate will be destroyed below.
1090 	 */
1091 	if (mnm == NULL) {
1092 		dv = dv_mkdir(ddv, devi, nm);
1093 	} else {
1094 		/*
1095 		 * For clone minors, load the driver indicated by minor name.
1096 		 */
1097 		mutex_enter(&DEVI(devi)->devi_lock);
1098 		if (devi == clone_dip) {
1099 			dv = dv_clone_mknod(ddv, mnm + 1);
1100 		} else {
1101 			/*
1102 			 * Find minor node and make a dv_node
1103 			 */
1104 			dmd = kmem_zalloc(sizeof (*dmd), KM_SLEEP);
1105 			if (dv_find_leafnode(devi, mnm + 1, dmd) == 0) {
1106 				dv = dv_mknod(ddv, devi, nm, dmd);
1107 				if (dmd->ddm_node_priv)
1108 					dpfree(dmd->ddm_node_priv);
1109 			}
1110 			kmem_free(dmd, sizeof (*dmd));
1111 		}
1112 		mutex_exit(&DEVI(devi)->devi_lock);
1113 	}
1114 	/*
1115 	 * Release hold from ndi_devi_config_one()
1116 	 */
1117 	ndi_rele_devi(devi);
1118 
1119 	if (dv == NULL) {
1120 		rv = ENOENT;
1121 		goto notfound;
1122 	}
1123 
1124 	/*
1125 	 * We have released the dv_contents lock, need to check
1126 	 * if another thread already created a duplicate node
1127 	 */
1128 	rw_enter(&ddv->dv_contents, RW_WRITER);
1129 	if ((dup = dv_findbyname(ddv, nm)) == NULL) {
1130 		dv_insert(ddv, dv);
1131 	} else {
1132 		/*
1133 		 * Duplicate found, use the existing node
1134 		 */
1135 		VN_RELE(DVTOV(dv));
1136 		dv_destroy(dv, 0);
1137 		dv = dup;
1138 	}
1139 	goto founddv;
1140 	/*NOTREACHED*/
1141 
1142 found:
1143 	/*
1144 	 * Skip non-kernel lookups of internal nodes.
1145 	 * This use of kcred to distinguish between user and
1146 	 * internal kernel lookups is unfortunate.  The information
1147 	 * provided by the seg argument to lookupnameat should
1148 	 * evolve into a lookup flag for filesystems that need
1149 	 * this distinction.
1150 	 */
1151 	if ((dv->dv_flags & DV_INTERNAL) && (cred != kcred)) {
1152 		VN_RELE(vp);
1153 		rv = ENOENT;
1154 		goto notfound;
1155 	}
1156 
1157 	dcmn_err2(("dv_find: returning vp for nm %s\n", nm));
1158 	if (vp->v_type == VCHR || vp->v_type == VBLK) {
1159 		/*
1160 		 * If vnode is a device, return special vnode instead
1161 		 * (though it knows all about -us- via sp->s_realvp,
1162 		 * sp->s_devvp, and sp->s_dip)
1163 		 */
1164 		*vpp = specvp_devfs(vp, vp->v_rdev, vp->v_type, cred,
1165 			dv->dv_devi);
1166 		VN_RELE(vp);
1167 		if (*vpp == NULLVP)
1168 			rv = ENOSYS;
1169 	} else
1170 		*vpp = vp;
1171 
1172 notfound:
1173 	rw_enter(&ddv->dv_contents, RW_WRITER);
1174 	if (was_busy)
1175 		ddv->dv_busy--;
1176 	rw_exit(&ddv->dv_contents);
1177 	return (rv);
1178 }
1179 
1180 /*
1181  * The given directory node is out-of-date; that is, it has been
1182  * marked as needing to be rebuilt, possibly because some new devinfo
1183  * node has come into existence, or possibly because this is the first
1184  * time we've been here.
1185  */
1186 void
1187 dv_filldir(struct dv_node *ddv)
1188 {
1189 	struct dv_node *dv;
1190 	dev_info_t *devi, *pdevi;
1191 	struct ddi_minor_data *dmd;
1192 	char devnm[MAXNAMELEN];
1193 	int circ;
1194 
1195 	ASSERT(DVTOV(ddv)->v_type == VDIR);
1196 	ASSERT(RW_WRITE_HELD(&ddv->dv_contents));
1197 	ASSERT(ddv->dv_flags & DV_BUILD);
1198 
1199 	dcmn_err3(("dv_filldir: %s\n", ddv->dv_name));
1200 	if (DV_STALE(ddv))
1201 		return;
1202 	pdevi = ddv->dv_devi;
1203 
1204 	if (ndi_devi_config(pdevi, NDI_NO_EVENT) != NDI_SUCCESS) {
1205 		dcmn_err3(("dv_filldir: config error %s\n",
1206 			ddv->dv_name));
1207 	}
1208 
1209 	ndi_devi_enter(pdevi, &circ);
1210 	for (devi = ddi_get_child(pdevi); devi;
1211 	    devi = ddi_get_next_sibling(devi)) {
1212 		if (i_ddi_node_state(devi) < DS_PROBED)
1213 			continue;
1214 
1215 		dcmn_err3(("dv_filldir: node %s\n", ddi_node_name(devi)));
1216 
1217 		mutex_enter(&DEVI(devi)->devi_lock);
1218 		for (dmd = DEVI(devi)->devi_minor; dmd; dmd = dmd->next) {
1219 			char *addr;
1220 
1221 			/*
1222 			 * Skip alias nodes, internal nodes, and nodes
1223 			 * without a name.  We allow DDM_DEFAULT nodes
1224 			 * to appear in readdir.
1225 			 */
1226 			if ((dmd->type == DDM_ALIAS) ||
1227 			    (dmd->type == DDM_INTERNAL_PATH) ||
1228 			    (dmd->ddm_name == NULL))
1229 				continue;
1230 
1231 			addr = ddi_get_name_addr(devi);
1232 			if (addr && *addr)
1233 				(void) sprintf(devnm, "%s@%s:%s",
1234 				    ddi_node_name(devi), addr, dmd->ddm_name);
1235 			else
1236 				(void) sprintf(devnm, "%s:%s",
1237 				    ddi_node_name(devi), dmd->ddm_name);
1238 
1239 			if ((dv = dv_findbyname(ddv, devnm)) != NULL) {
1240 				/* dv_node already exists */
1241 				VN_RELE(DVTOV(dv));
1242 				continue;
1243 			}
1244 
1245 			dv = dv_mknod(ddv, devi, devnm, dmd);
1246 			dv_insert(ddv, dv);
1247 			VN_RELE(DVTOV(dv));
1248 		}
1249 		mutex_exit(&DEVI(devi)->devi_lock);
1250 
1251 		(void) ddi_deviname(devi, devnm);
1252 		if ((dv = dv_findbyname(ddv, devnm + 1)) == NULL) {
1253 			/* directory doesn't exist */
1254 			dv = dv_mkdir(ddv, devi, devnm + 1);
1255 			dv_insert(ddv, dv);
1256 		}
1257 		VN_RELE(DVTOV(dv));
1258 	}
1259 	ndi_devi_exit(pdevi, circ);
1260 
1261 	ddv->dv_flags &= ~DV_BUILD;
1262 }
1263 
1264 /*
1265  * Given a directory node, clean out all the nodes beneath.
1266  *
1267  * VDIR:	Reinvoke to clean them, then delete the directory.
1268  * VCHR, VBLK:	Just blow them away.
1269  *
1270  * Mark the directories touched as in need of a rebuild, in case
1271  * we fall over part way through. When DV_CLEAN_FORCE is specified,
1272  * we mark referenced empty directories as stale to facilitate DR.
1273  */
1274 int
1275 dv_cleandir(struct dv_node *ddv, char *devnm, uint_t flags)
1276 {
1277 	struct dv_node *dv;
1278 	struct dv_node **pprev, **npprev;
1279 	struct vnode *vp;
1280 	int busy = 0;
1281 
1282 	/*
1283 	 * We should always be holding the tsd_clean_key here: dv_cleandir()
1284 	 * will be called as a result of a devfs_clean request and the
1285 	 * tsd_clean_key will be set in either in devfs_clean() itself or in
1286 	 * devfs_clean_vhci().
1287 	 *
1288 	 * Since we are on the devfs_clean path, we return EBUSY if we cannot
1289 	 * get the contents lock: if we blocked here we might deadlock against
1290 	 * a thread performing top-down device configuration.
1291 	 */
1292 	ASSERT(tsd_get(devfs_clean_key));
1293 
1294 	dcmn_err3(("dv_cleandir: %s\n", ddv->dv_name));
1295 
1296 	if (!(flags & DV_CLEANDIR_LCK) &&
1297 	    !rw_tryenter(&ddv->dv_contents, RW_WRITER))
1298 		return (EBUSY);
1299 
1300 	for (pprev = &ddv->dv_dot, dv = *pprev; dv;
1301 	    pprev = npprev, dv = *pprev) {
1302 		npprev = &dv->dv_next;
1303 
1304 		/*
1305 		 * If devnm is specified, the non-minor portion of the
1306 		 * name must match devnm.
1307 		 */
1308 		if (devnm &&
1309 		    (strncmp(devnm, dv->dv_name, strlen(devnm)) ||
1310 		    (dv->dv_name[strlen(devnm)] != ':' &&
1311 		    dv->dv_name[strlen(devnm)] != '\0')))
1312 			continue;
1313 
1314 		/* check type of what we are cleaning */
1315 		vp = DVTOV(dv);
1316 		if (vp->v_type == VDIR) {
1317 			/* recurse on directories */
1318 			rw_enter(&dv->dv_contents, RW_WRITER);
1319 			if (dv_cleandir(dv, NULL,
1320 			    flags | DV_CLEANDIR_LCK) == EBUSY) {
1321 				rw_exit(&dv->dv_contents);
1322 				goto set_busy;
1323 			}
1324 
1325 			/* A clean directory is an empty directory... */
1326 			ASSERT(dv->dv_nlink == 2);
1327 			mutex_enter(&vp->v_lock);
1328 			if (vp->v_count > 0) {
1329 				/*
1330 				 * ... but an empty directory can still have
1331 				 * references to it. If we have dv_busy or
1332 				 * DV_CLEAN_FORCE is *not* specified then a
1333 				 * referenced directory is considered busy.
1334 				 */
1335 				if (dv->dv_busy || !(flags & DV_CLEAN_FORCE)) {
1336 					mutex_exit(&vp->v_lock);
1337 					rw_exit(&dv->dv_contents);
1338 					goto set_busy;
1339 				}
1340 
1341 				/*
1342 				 * Mark referenced directory stale so that DR
1343 				 * will succeed even if a shell has
1344 				 * /devices/xxx as current directory (causing
1345 				 * VN_HOLD reference to an empty directory).
1346 				 */
1347 				ASSERT(!DV_STALE(dv));
1348 				ndi_rele_devi(dv->dv_devi);
1349 				dv->dv_devi = NULL;	/* mark DV_STALE */
1350 			}
1351 		} else {
1352 			ASSERT((vp->v_type == VCHR) || (vp->v_type == VBLK));
1353 			ASSERT(dv->dv_nlink == 1);	/* no hard links */
1354 			mutex_enter(&vp->v_lock);
1355 			if (vp->v_count > 0) {
1356 				mutex_exit(&vp->v_lock);
1357 				goto set_busy;
1358 			}
1359 		}
1360 
1361 		/* unlink from directory */
1362 		dv_unlink(ddv, dv, pprev);
1363 
1364 		/* drop locks */
1365 		mutex_exit(&vp->v_lock);
1366 		if (vp->v_type == VDIR)
1367 			rw_exit(&dv->dv_contents);
1368 
1369 		/* destroy vnode if ref count is zero */
1370 		if (vp->v_count == 0)
1371 			dv_destroy(dv, flags);
1372 
1373 		/* pointer to previous stays unchanged */
1374 		npprev = pprev;
1375 		continue;
1376 
1377 		/*
1378 		 * If devnm is not NULL we return immediately on busy,
1379 		 * otherwise we continue destroying unused dv_node's.
1380 		 */
1381 set_busy:	busy++;
1382 		if (devnm)
1383 			break;
1384 	}
1385 
1386 	/*
1387 	 * This code may be invoked to inform devfs that a new node has
1388 	 * been created in the kernel device tree. So we always set
1389 	 * the DV_BUILD flag to allow the next dv_filldir() to pick
1390 	 * the new devinfo nodes.
1391 	 */
1392 	ddv->dv_flags |= DV_BUILD;
1393 
1394 	if (!(flags & DV_CLEANDIR_LCK))
1395 		rw_exit(&ddv->dv_contents);
1396 
1397 	return (busy ? EBUSY : 0);
1398 }
1399 
1400 /*
1401  * Walk through the devfs hierarchy, correcting the permissions of
1402  * devices with default permissions that do not match those specified
1403  * by minor perm.  This can only be done for all drivers for now.
1404  */
1405 static int
1406 dv_reset_perm_dir(struct dv_node *ddv, uint_t flags)
1407 {
1408 	struct dv_node *dv, *next = NULL;
1409 	struct vnode *vp;
1410 	int retval = 0;
1411 	struct vattr *attrp;
1412 	mperm_t mp;
1413 	char *nm;
1414 	uid_t old_uid;
1415 	gid_t old_gid;
1416 	mode_t old_mode;
1417 
1418 	rw_enter(&ddv->dv_contents, RW_WRITER);
1419 	for (dv = ddv->dv_dot; dv; dv = next) {
1420 		int error = 0;
1421 		next = dv->dv_next;
1422 		nm = dv->dv_name;
1423 
1424 		rw_enter(&dv->dv_contents, RW_READER);
1425 		vp = DVTOV(dv);
1426 		if (vp->v_type == VDIR) {
1427 			rw_exit(&dv->dv_contents);
1428 			if (dv_reset_perm_dir(dv, flags) != 0) {
1429 				error = EBUSY;
1430 			}
1431 		} else {
1432 			ASSERT(vp->v_type == VCHR || vp->v_type == VBLK);
1433 
1434 			/*
1435 			 * Check for permissions from minor_perm
1436 			 * If there are none, we're done
1437 			 */
1438 			rw_exit(&dv->dv_contents);
1439 			if (dev_minorperm(dv->dv_devi, nm, &mp) != 0)
1440 				continue;
1441 
1442 			rw_enter(&dv->dv_contents, RW_READER);
1443 
1444 			/*
1445 			 * Allow a node's permissions to be altered
1446 			 * permanently from the defaults by chmod,
1447 			 * using the shadow node as backing store.
1448 			 * Otherwise, update node to minor_perm permissions.
1449 			 */
1450 			if (dv->dv_attrvp == NULLVP) {
1451 				/*
1452 				 * No attribute vp, try to find one.
1453 				 */
1454 				dv_shadow_node(DVTOV(ddv), nm, vp,
1455 					NULL, NULLVP, kcred, 0);
1456 			}
1457 			if (dv->dv_attrvp != NULLVP || dv->dv_attr == NULL) {
1458 				rw_exit(&dv->dv_contents);
1459 				continue;
1460 			}
1461 
1462 			attrp = dv->dv_attr;
1463 
1464 			if (VATTRP_MP_CMP(attrp, mp) == 0) {
1465 				dcmn_err5(("%s: no perm change: "
1466 				    "%d %d 0%o\n", nm, attrp->va_uid,
1467 				    attrp->va_gid, attrp->va_mode));
1468 				rw_exit(&dv->dv_contents);
1469 				continue;
1470 			}
1471 
1472 			old_uid = attrp->va_uid;
1473 			old_gid = attrp->va_gid;
1474 			old_mode = attrp->va_mode;
1475 
1476 			VATTRP_MP_MERGE(attrp, mp);
1477 			mutex_enter(&vp->v_lock);
1478 			if (vp->v_count > 0) {
1479 				error = EBUSY;
1480 			}
1481 			mutex_exit(&vp->v_lock);
1482 
1483 			dcmn_err5(("%s: perm %d/%d/0%o -> %d/%d/0%o (%d)\n",
1484 			    nm, old_uid, old_gid, old_mode, attrp->va_uid,
1485 			    attrp->va_gid, attrp->va_mode, error));
1486 
1487 			rw_exit(&dv->dv_contents);
1488 		}
1489 
1490 		if (error != 0) {
1491 			retval = error;
1492 		}
1493 	}
1494 
1495 	ddv->dv_flags |= DV_BUILD;
1496 
1497 	rw_exit(&ddv->dv_contents);
1498 
1499 	return (retval);
1500 }
1501 
1502 int
1503 devfs_reset_perm(uint_t flags)
1504 {
1505 	struct dv_node *dvp;
1506 	int rval;
1507 
1508 	if ((dvp = devfs_dip_to_dvnode(ddi_root_node())) == NULL)
1509 		return (0);
1510 
1511 	VN_HOLD(DVTOV(dvp));
1512 	rval = dv_reset_perm_dir(dvp, flags);
1513 	VN_RELE(DVTOV(dvp));
1514 	return (rval);
1515 }
1516 
1517 /*
1518  * Clean up dangling devfs shadow nodes for removed
1519  * drivers so that, in the event the driver is re-added
1520  * to the system, newly created nodes won't incorrectly
1521  * pick up these stale shadow node permissions.
1522  *
1523  * This is accomplished by walking down the pathname
1524  * to the directory, starting at the root's attribute
1525  * node, then removing all minors matching the specified
1526  * node name.  Care must be taken to remove all entries
1527  * in a directory before the directory itself, so that
1528  * the clean-up associated with rem_drv'ing a nexus driver
1529  * does not inadvertently result in an inconsistent
1530  * filesystem underlying devfs.
1531  */
1532 
1533 static int
1534 devfs_remdrv_rmdir(vnode_t *dirvp, const char *dir, vnode_t *rvp)
1535 {
1536 	int error;
1537 	vnode_t *vp;
1538 	int eof;
1539 	struct iovec iov;
1540 	struct uio uio;
1541 	struct dirent64 *dp;
1542 	dirent64_t *dbuf;
1543 	size_t dlen;
1544 	size_t dbuflen;
1545 	int ndirents = 64;
1546 	char *nm;
1547 
1548 	VN_HOLD(dirvp);
1549 
1550 	dlen = ndirents * (sizeof (*dbuf));
1551 	dbuf = kmem_alloc(dlen, KM_SLEEP);
1552 
1553 	uio.uio_iov = &iov;
1554 	uio.uio_iovcnt = 1;
1555 	uio.uio_segflg = UIO_SYSSPACE;
1556 	uio.uio_fmode = 0;
1557 	uio.uio_extflg = UIO_COPY_CACHED;
1558 	uio.uio_loffset = 0;
1559 	uio.uio_llimit = MAXOFFSET_T;
1560 
1561 	eof = 0;
1562 	error = 0;
1563 	while (!error && !eof) {
1564 		uio.uio_resid = dlen;
1565 		iov.iov_base = (char *)dbuf;
1566 		iov.iov_len = dlen;
1567 
1568 		(void) VOP_RWLOCK(dirvp, V_WRITELOCK_FALSE, NULL);
1569 		error = VOP_READDIR(dirvp, &uio, kcred, &eof);
1570 		VOP_RWUNLOCK(dirvp, V_WRITELOCK_FALSE, NULL);
1571 
1572 		dbuflen = dlen - uio.uio_resid;
1573 
1574 		if (error || dbuflen == 0)
1575 			break;
1576 
1577 		for (dp = dbuf; ((intptr_t)dp < (intptr_t)dbuf + dbuflen);
1578 			dp = (dirent64_t *)((intptr_t)dp + dp->d_reclen)) {
1579 
1580 			nm = dp->d_name;
1581 
1582 			if (strcmp(nm, ".") == 0 || strcmp(nm, "..") == 0)
1583 				continue;
1584 
1585 			error = VOP_LOOKUP(dirvp,
1586 				nm, &vp, NULL, 0, NULL, kcred);
1587 
1588 			dsysdebug(error,
1589 			    ("rem_drv %s/%s lookup (%d)\n",
1590 			    dir, nm, error));
1591 
1592 			if (error)
1593 				continue;
1594 
1595 			ASSERT(vp->v_type == VDIR ||
1596 				vp->v_type == VCHR || vp->v_type == VBLK);
1597 
1598 			if (vp->v_type == VDIR) {
1599 				error = devfs_remdrv_rmdir(vp, nm, rvp);
1600 				if (error == 0) {
1601 					error = VOP_RMDIR(dirvp,
1602 					    (char *)nm, rvp, kcred);
1603 					dsysdebug(error,
1604 					    ("rem_drv %s/%s rmdir (%d)\n",
1605 					    dir, nm, error));
1606 				}
1607 			} else {
1608 				error = VOP_REMOVE(dirvp, (char *)nm, kcred);
1609 				dsysdebug(error,
1610 				    ("rem_drv %s/%s remove (%d)\n",
1611 				    dir, nm, error));
1612 			}
1613 
1614 			VN_RELE(vp);
1615 			if (error) {
1616 				goto exit;
1617 			}
1618 		}
1619 	}
1620 
1621 exit:
1622 	VN_RELE(dirvp);
1623 	kmem_free(dbuf, dlen);
1624 
1625 	return (error);
1626 }
1627 
1628 int
1629 devfs_remdrv_cleanup(const char *dir, const char *nodename)
1630 {
1631 	int error;
1632 	vnode_t *vp;
1633 	vnode_t *dirvp;
1634 	int eof;
1635 	struct iovec iov;
1636 	struct uio uio;
1637 	struct dirent64 *dp;
1638 	dirent64_t *dbuf;
1639 	size_t dlen;
1640 	size_t dbuflen;
1641 	int ndirents = 64;
1642 	int nodenamelen = strlen(nodename);
1643 	char *nm;
1644 	struct pathname pn;
1645 	vnode_t *rvp;		/* root node of the underlying attribute fs */
1646 
1647 	dcmn_err5(("devfs_remdrv_cleanup: %s %s\n", dir, nodename));
1648 
1649 	if (error = pn_get((char *)dir, UIO_SYSSPACE, &pn))
1650 		return (0);
1651 
1652 	rvp = dvroot->dv_attrvp;
1653 	ASSERT(rvp != NULL);
1654 	VN_HOLD(rvp);
1655 
1656 	pn_skipslash(&pn);
1657 	dirvp = rvp;
1658 	VN_HOLD(dirvp);
1659 
1660 	nm = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1661 
1662 	while (pn_pathleft(&pn)) {
1663 		ASSERT(dirvp->v_type == VDIR);
1664 		(void) pn_getcomponent(&pn, nm);
1665 		ASSERT((strcmp(nm, ".") != 0) && (strcmp(nm, "..") != 0));
1666 		error = VOP_LOOKUP(dirvp, nm, &vp, NULL, 0, rvp, kcred);
1667 		if (error) {
1668 			dcmn_err5(("remdrv_cleanup %s lookup error %d\n",
1669 			    nm, error));
1670 			VN_RELE(dirvp);
1671 			if (dirvp != rvp)
1672 				VN_RELE(rvp);
1673 			pn_free(&pn);
1674 			kmem_free(nm, MAXNAMELEN);
1675 			return (0);
1676 		}
1677 		VN_RELE(dirvp);
1678 		dirvp = vp;
1679 		pn_skipslash(&pn);
1680 	}
1681 
1682 	ASSERT(dirvp->v_type == VDIR);
1683 	if (dirvp != rvp)
1684 		VN_RELE(rvp);
1685 	pn_free(&pn);
1686 	kmem_free(nm, MAXNAMELEN);
1687 
1688 	dlen = ndirents * (sizeof (*dbuf));
1689 	dbuf = kmem_alloc(dlen, KM_SLEEP);
1690 
1691 	uio.uio_iov = &iov;
1692 	uio.uio_iovcnt = 1;
1693 	uio.uio_segflg = UIO_SYSSPACE;
1694 	uio.uio_fmode = 0;
1695 	uio.uio_extflg = UIO_COPY_CACHED;
1696 	uio.uio_loffset = 0;
1697 	uio.uio_llimit = MAXOFFSET_T;
1698 
1699 	eof = 0;
1700 	error = 0;
1701 	while (!error && !eof) {
1702 		uio.uio_resid = dlen;
1703 		iov.iov_base = (char *)dbuf;
1704 		iov.iov_len = dlen;
1705 
1706 		(void) VOP_RWLOCK(dirvp, V_WRITELOCK_FALSE, NULL);
1707 		error = VOP_READDIR(dirvp, &uio, kcred, &eof);
1708 		VOP_RWUNLOCK(dirvp, V_WRITELOCK_FALSE, NULL);
1709 
1710 		dbuflen = dlen - uio.uio_resid;
1711 
1712 		if (error || dbuflen == 0)
1713 			break;
1714 
1715 		for (dp = dbuf; ((intptr_t)dp < (intptr_t)dbuf + dbuflen);
1716 			dp = (dirent64_t *)((intptr_t)dp + dp->d_reclen)) {
1717 
1718 			nm = dp->d_name;
1719 
1720 			if (strcmp(nm, ".") == 0 || strcmp(nm, "..") == 0)
1721 				continue;
1722 
1723 			if (strncmp(nm, nodename, nodenamelen) != 0)
1724 				continue;
1725 
1726 			error = VOP_LOOKUP(dirvp, nm, &vp,
1727 			    NULL, 0, NULL, kcred);
1728 
1729 			dsysdebug(error,
1730 			    ("rem_drv %s/%s lookup (%d)\n",
1731 			    dir, nm, error));
1732 
1733 			if (error)
1734 				continue;
1735 
1736 			ASSERT(vp->v_type == VDIR ||
1737 				vp->v_type == VCHR || vp->v_type == VBLK);
1738 
1739 			if (vp->v_type == VDIR) {
1740 				error = devfs_remdrv_rmdir(vp, nm, rvp);
1741 				if (error == 0) {
1742 					error = VOP_RMDIR(dirvp,
1743 					    (char *)nm, rvp, kcred);
1744 					dsysdebug(error,
1745 					    ("rem_drv %s/%s rmdir (%d)\n",
1746 					    dir, nm, error));
1747 				}
1748 			} else {
1749 				error = VOP_REMOVE(dirvp, (char *)nm, kcred);
1750 				dsysdebug(error,
1751 				    ("rem_drv %s/%s remove (%d)\n",
1752 				    dir, nm, error));
1753 			}
1754 
1755 			VN_RELE(vp);
1756 			if (error)
1757 				goto exit;
1758 		}
1759 	}
1760 
1761 exit:
1762 	VN_RELE(dirvp);
1763 
1764 	kmem_free(dbuf, dlen);
1765 
1766 	return (0);
1767 }
1768 
1769 struct dv_list {
1770 	struct dv_node	*dv;
1771 	struct dv_list	*next;
1772 };
1773 
1774 void
1775 dv_walk(
1776 	struct dv_node	*ddv,
1777 	char		*devnm,
1778 	void		(*callback)(struct dv_node *, void *),
1779 	void		*arg)
1780 {
1781 	struct vnode	*dvp;
1782 	struct dv_node	*dv;
1783 	struct dv_list	*head, *tail, *next;
1784 	int		len;
1785 
1786 	dcmn_err3(("dv_walk: ddv = %s, devnm = %s\n",
1787 	    ddv->dv_name, devnm ? devnm : "<null>"));
1788 
1789 	dvp = DVTOV(ddv);
1790 
1791 	ASSERT(dvp->v_type == VDIR);
1792 
1793 	head = tail = next = NULL;
1794 
1795 	rw_enter(&ddv->dv_contents, RW_READER);
1796 	mutex_enter(&dvp->v_lock);
1797 	for (dv = ddv->dv_dot; dv; dv = dv->dv_next) {
1798 		/*
1799 		 * If devnm is not NULL and is not the empty string,
1800 		 * select only dv_nodes with matching non-minor name
1801 		 */
1802 		if (devnm && (len = strlen(devnm)) &&
1803 		    (strncmp(devnm, dv->dv_name, len) ||
1804 		    (dv->dv_name[len] != ':' && dv->dv_name[len] != '\0')))
1805 			continue;
1806 
1807 		callback(dv, arg);
1808 
1809 		if (DVTOV(dv)->v_type != VDIR)
1810 			continue;
1811 
1812 		next = kmem_zalloc(sizeof (*next), KM_SLEEP);
1813 		next->dv = dv;
1814 
1815 		if (tail)
1816 			tail->next = next;
1817 		else
1818 			head = next;
1819 
1820 		tail = next;
1821 	}
1822 
1823 	while (head) {
1824 		dv_walk(head->dv, NULL, callback, arg);
1825 		next = head->next;
1826 		kmem_free(head, sizeof (*head));
1827 		head = next;
1828 	}
1829 	rw_exit(&ddv->dv_contents);
1830 	mutex_exit(&dvp->v_lock);
1831 }
1832