xref: /openbsd-src/sys/kern/vfs_subr.c (revision 10dc078528519b6d34f2083e65dda8cc55239771)
1 /*	$OpenBSD: vfs_subr.c,v 1.307 2021/10/19 06:26:08 semarie Exp $	*/
2 /*	$NetBSD: vfs_subr.c,v 1.53 1996/04/22 01:39:13 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)vfs_subr.c	8.13 (Berkeley) 4/18/94
38  */
39 
40 /*
41  * External virtual filesystem routines
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/proc.h>
47 #include <sys/sysctl.h>
48 #include <sys/mount.h>
49 #include <sys/time.h>
50 #include <sys/fcntl.h>
51 #include <sys/kernel.h>
52 #include <sys/conf.h>
53 #include <sys/vnode.h>
54 #include <sys/lock.h>
55 #include <sys/lockf.h>
56 #include <sys/stat.h>
57 #include <sys/acct.h>
58 #include <sys/namei.h>
59 #include <sys/ucred.h>
60 #include <sys/buf.h>
61 #include <sys/errno.h>
62 #include <sys/malloc.h>
63 #include <sys/mbuf.h>
64 #include <sys/syscallargs.h>
65 #include <sys/pool.h>
66 #include <sys/tree.h>
67 #include <sys/specdev.h>
68 #include <sys/atomic.h>
69 
70 #include <netinet/in.h>
71 
72 #include <uvm/uvm_extern.h>
73 #include <uvm/uvm_vnode.h>
74 
75 #include "softraid.h"
76 
77 void sr_quiesce(void);
78 
79 enum vtype iftovt_tab[16] = {
80 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
81 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
82 };
83 
84 int	vttoif_tab[9] = {
85 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
86 	S_IFSOCK, S_IFIFO, S_IFMT,
87 };
88 
89 int prtactive = 0;		/* 1 => print out reclaim of active vnodes */
90 int suid_clear = 1;		/* 1 => clear SUID / SGID on owner change */
91 
92 /*
93  * Insq/Remq for the vnode usage lists.
94  */
95 #define	bufinsvn(bp, dp)	LIST_INSERT_HEAD(dp, bp, b_vnbufs)
96 #define	bufremvn(bp) {							\
97 	LIST_REMOVE(bp, b_vnbufs);					\
98 	LIST_NEXT(bp, b_vnbufs) = NOLIST;				\
99 }
100 
101 struct freelst vnode_hold_list;	/* list of vnodes referencing buffers */
102 struct freelst vnode_free_list;	/* vnode free list */
103 
104 struct mntlist mountlist;	/* mounted filesystem list */
105 
106 void	vclean(struct vnode *, int, struct proc *);
107 
108 void insmntque(struct vnode *, struct mount *);
109 int getdevvp(dev_t, struct vnode **, enum vtype);
110 
111 int vfs_hang_addrlist(struct mount *, struct netexport *,
112 				  struct export_args *);
113 int vfs_free_netcred(struct radix_node *, void *, u_int);
114 void vfs_free_addrlist(struct netexport *);
115 void vputonfreelist(struct vnode *);
116 
117 int vflush_vnode(struct vnode *, void *);
118 int maxvnodes;
119 
120 struct mutex vnode_mtx = MUTEX_INITIALIZER(IPL_BIO);
121 
122 void vfs_unmountall(void);
123 
124 #ifdef DEBUG
125 void printlockedvnodes(void);
126 #endif
127 
128 struct pool vnode_pool;
129 struct pool uvm_vnode_pool;
130 
131 static inline int rb_buf_compare(const struct buf *b1, const struct buf *b2);
132 RBT_GENERATE(buf_rb_bufs, buf, b_rbbufs, rb_buf_compare);
133 
134 static inline int
135 rb_buf_compare(const struct buf *b1, const struct buf *b2)
136 {
137 	if (b1->b_lblkno < b2->b_lblkno)
138 		return(-1);
139 	if (b1->b_lblkno > b2->b_lblkno)
140 		return(1);
141 	return(0);
142 }
143 
144 /*
145  * Initialize the vnode management data structures.
146  */
147 void
148 vntblinit(void)
149 {
150 	/* buffer cache may need a vnode for each buffer */
151 	maxvnodes = 2 * initialvnodes;
152 	pool_init(&vnode_pool, sizeof(struct vnode), 0, IPL_NONE,
153 	    PR_WAITOK, "vnodes", NULL);
154 	pool_init(&uvm_vnode_pool, sizeof(struct uvm_vnode), 0, IPL_NONE,
155 	    PR_WAITOK, "uvmvnodes", NULL);
156 	TAILQ_INIT(&vnode_hold_list);
157 	TAILQ_INIT(&vnode_free_list);
158 	TAILQ_INIT(&mountlist);
159 	/*
160 	 * Initialize the filesystem syncer.
161 	 */
162 	vn_initialize_syncerd();
163 
164 #ifdef NFSSERVER
165 	rn_init(sizeof(struct sockaddr_in));
166 #endif /* NFSSERVER */
167 }
168 
169 /*
170  * Allocate a mount point.
171  *
172  * The returned mount point is marked as busy.
173  */
174 struct mount *
175 vfs_mount_alloc(struct vnode *vp, struct vfsconf *vfsp)
176 {
177 	struct mount *mp;
178 
179 	mp = malloc(sizeof(*mp), M_MOUNT, M_WAITOK|M_ZERO);
180 	rw_init_flags(&mp->mnt_lock, "vfslock", RWL_IS_VNODE);
181 	(void)vfs_busy(mp, VB_READ|VB_NOWAIT);
182 
183 	TAILQ_INIT(&mp->mnt_vnodelist);
184 	mp->mnt_vnodecovered = vp;
185 
186 	atomic_inc_int(&vfsp->vfc_refcount);
187 	mp->mnt_vfc = vfsp;
188 	mp->mnt_op = vfsp->vfc_vfsops;
189 	mp->mnt_flag = vfsp->vfc_flags;
190 	strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
191 
192 	return (mp);
193 }
194 
195 /*
196  * Release a mount point.
197  */
198 void
199 vfs_mount_free(struct mount *mp)
200 {
201 	atomic_dec_int(&mp->mnt_vfc->vfc_refcount);
202 	free(mp, M_MOUNT, sizeof(*mp));
203 }
204 
205 /*
206  * Mark a mount point as busy. Used to synchronize access and to delay
207  * unmounting.
208  *
209  * Default behaviour is to attempt getting a READ lock and in case of an
210  * ongoing unmount, to wait for it to finish and then return failure.
211  */
212 int
213 vfs_busy(struct mount *mp, int flags)
214 {
215 	int rwflags = 0;
216 
217 	if (flags & VB_WRITE)
218 		rwflags |= RW_WRITE;
219 	else
220 		rwflags |= RW_READ;
221 
222 	if (flags & VB_WAIT)
223 		rwflags |= RW_SLEEPFAIL;
224 	else
225 		rwflags |= RW_NOSLEEP;
226 
227 #ifdef WITNESS
228 	if (flags & VB_DUPOK)
229 		rwflags |= RW_DUPOK;
230 #endif
231 
232 	if (rw_enter(&mp->mnt_lock, rwflags))
233 		return (EBUSY);
234 
235 	return (0);
236 }
237 
238 /*
239  * Free a busy file system
240  */
241 void
242 vfs_unbusy(struct mount *mp)
243 {
244 	rw_exit(&mp->mnt_lock);
245 }
246 
247 int
248 vfs_isbusy(struct mount *mp)
249 {
250 	if (RWLOCK_OWNER(&mp->mnt_lock) > 0)
251 		return (1);
252 	else
253 		return (0);
254 }
255 
256 /*
257  * Lookup a filesystem type, and if found allocate and initialize
258  * a mount structure for it.
259  *
260  * Devname is usually updated by mount(8) after booting.
261  */
262 int
263 vfs_rootmountalloc(char *fstypename, char *devname, struct mount **mpp)
264 {
265 	struct vfsconf *vfsp;
266 	struct mount *mp;
267 
268 	vfsp = vfs_byname(fstypename);
269 	if (vfsp == NULL)
270 		return (ENODEV);
271 	mp = vfs_mount_alloc(NULLVP, vfsp);
272 	mp->mnt_flag |= MNT_RDONLY;
273 	mp->mnt_stat.f_mntonname[0] = '/';
274 	copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN, 0);
275 	copystr(devname, mp->mnt_stat.f_mntfromspec, MNAMELEN, 0);
276 	*mpp = mp;
277 	return (0);
278  }
279 
280 /*
281  * Lookup a mount point by filesystem identifier.
282  */
283 struct mount *
284 vfs_getvfs(fsid_t *fsid)
285 {
286 	struct mount *mp;
287 
288 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
289 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
290 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
291 			return (mp);
292 		}
293 	}
294 
295 	return (NULL);
296 }
297 
298 
299 /*
300  * Get a new unique fsid
301  */
302 void
303 vfs_getnewfsid(struct mount *mp)
304 {
305 	static u_short xxxfs_mntid;
306 
307 	fsid_t tfsid;
308 	int mtype;
309 
310 	mtype = mp->mnt_vfc->vfc_typenum;
311 	mp->mnt_stat.f_fsid.val[0] = makedev(nblkdev + mtype, 0);
312 	mp->mnt_stat.f_fsid.val[1] = mtype;
313 	if (xxxfs_mntid == 0)
314 		++xxxfs_mntid;
315 	tfsid.val[0] = makedev(nblkdev + mtype, xxxfs_mntid);
316 	tfsid.val[1] = mtype;
317 	if (!TAILQ_EMPTY(&mountlist)) {
318 		while (vfs_getvfs(&tfsid)) {
319 			tfsid.val[0]++;
320 			xxxfs_mntid++;
321 		}
322 	}
323 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
324 }
325 
326 /*
327  * Set vnode attributes to VNOVAL
328  */
329 void
330 vattr_null(struct vattr *vap)
331 {
332 
333 	vap->va_type = VNON;
334 	/*
335 	 * Don't get fancy: u_quad_t = u_int = VNOVAL leaves the u_quad_t
336 	 * with 2^31-1 instead of 2^64-1.  Just write'm out and let
337 	 * the compiler do its job.
338 	 */
339 	vap->va_mode = VNOVAL;
340 	vap->va_nlink = VNOVAL;
341 	vap->va_uid = VNOVAL;
342 	vap->va_gid = VNOVAL;
343 	vap->va_fsid = VNOVAL;
344 	vap->va_fileid = VNOVAL;
345 	vap->va_size = VNOVAL;
346 	vap->va_blocksize = VNOVAL;
347 	vap->va_atime.tv_sec = VNOVAL;
348 	vap->va_atime.tv_nsec = VNOVAL;
349 	vap->va_mtime.tv_sec = VNOVAL;
350 	vap->va_mtime.tv_nsec = VNOVAL;
351 	vap->va_ctime.tv_sec = VNOVAL;
352 	vap->va_ctime.tv_nsec = VNOVAL;
353 	vap->va_gen = VNOVAL;
354 	vap->va_flags = VNOVAL;
355 	vap->va_rdev = VNOVAL;
356 	vap->va_bytes = VNOVAL;
357 	vap->va_filerev = VNOVAL;
358 	vap->va_vaflags = 0;
359 }
360 
361 /*
362  * Routines having to do with the management of the vnode table.
363  */
364 long numvnodes;
365 
366 /*
367  * Return the next vnode from the free list.
368  */
369 int
370 getnewvnode(enum vtagtype tag, struct mount *mp, const struct vops *vops,
371     struct vnode **vpp)
372 {
373 	struct proc *p = curproc;
374 	struct freelst *listhd;
375 	static int toggle;
376 	struct vnode *vp;
377 	int s;
378 
379 	/*
380 	 * allow maxvnodes to increase if the buffer cache itself
381 	 * is big enough to justify it. (we don't shrink it ever)
382 	 */
383 	maxvnodes = maxvnodes < bcstats.numbufs ? bcstats.numbufs
384 	    : maxvnodes;
385 
386 	/*
387 	 * We must choose whether to allocate a new vnode or recycle an
388 	 * existing one. The criterion for allocating a new one is that
389 	 * the total number of vnodes is less than the number desired or
390 	 * there are no vnodes on either free list. Generally we only
391 	 * want to recycle vnodes that have no buffers associated with
392 	 * them, so we look first on the vnode_free_list. If it is empty,
393 	 * we next consider vnodes with referencing buffers on the
394 	 * vnode_hold_list. The toggle ensures that half the time we
395 	 * will use a buffer from the vnode_hold_list, and half the time
396 	 * we will allocate a new one unless the list has grown to twice
397 	 * the desired size. We are reticent to recycle vnodes from the
398 	 * vnode_hold_list because we will lose the identity of all its
399 	 * referencing buffers.
400 	 */
401 	toggle ^= 1;
402 	if (numvnodes / 2 > maxvnodes)
403 		toggle = 0;
404 
405 	s = splbio();
406 	if ((numvnodes < maxvnodes) ||
407 	    ((TAILQ_FIRST(listhd = &vnode_free_list) == NULL) &&
408 	    ((TAILQ_FIRST(listhd = &vnode_hold_list) == NULL) || toggle))) {
409 		splx(s);
410 		vp = pool_get(&vnode_pool, PR_WAITOK | PR_ZERO);
411 		vp->v_uvm = pool_get(&uvm_vnode_pool, PR_WAITOK | PR_ZERO);
412 		vp->v_uvm->u_vnode = vp;
413 		RBT_INIT(buf_rb_bufs, &vp->v_bufs_tree);
414 		cache_tree_init(&vp->v_nc_tree);
415 		TAILQ_INIT(&vp->v_cache_dst);
416 		numvnodes++;
417 	} else {
418 		TAILQ_FOREACH(vp, listhd, v_freelist) {
419 			if (VOP_ISLOCKED(vp) == 0)
420 				break;
421 		}
422 		/*
423 		 * Unless this is a bad time of the month, at most
424 		 * the first NCPUS items on the free list are
425 		 * locked, so this is close enough to being empty.
426 		 */
427 		if (vp == NULL) {
428 			splx(s);
429 			tablefull("vnode");
430 			*vpp = 0;
431 			return (ENFILE);
432 		}
433 
434 #ifdef DIAGNOSTIC
435 		if (vp->v_usecount) {
436 			vprint("free vnode", vp);
437 			panic("free vnode isn't");
438 		}
439 #endif
440 
441 		TAILQ_REMOVE(listhd, vp, v_freelist);
442 		vp->v_bioflag &= ~VBIOONFREELIST;
443 		splx(s);
444 
445 		if (vp->v_type != VBAD)
446 			vgonel(vp, p);
447 #ifdef DIAGNOSTIC
448 		if (vp->v_data) {
449 			vprint("cleaned vnode", vp);
450 			panic("cleaned vnode isn't");
451 		}
452 		s = splbio();
453 		if (vp->v_numoutput)
454 			panic("Clean vnode has pending I/O's");
455 		splx(s);
456 #endif
457 		vp->v_flag = 0;
458 		vp->v_socket = NULL;
459 	}
460 	cache_purge(vp);
461 	vp->v_type = VNON;
462 	vp->v_tag = tag;
463 	vp->v_op = vops;
464 	insmntque(vp, mp);
465 	*vpp = vp;
466 	vp->v_usecount = 1;
467 	vp->v_data = 0;
468 	return (0);
469 }
470 
471 /*
472  * Move a vnode from one mount queue to another.
473  */
474 void
475 insmntque(struct vnode *vp, struct mount *mp)
476 {
477 	/*
478 	 * Delete from old mount point vnode list, if on one.
479 	 */
480 	if (vp->v_mount != NULL)
481 		TAILQ_REMOVE(&vp->v_mount->mnt_vnodelist, vp, v_mntvnodes);
482 	/*
483 	 * Insert into list of vnodes for the new mount point, if available.
484 	 */
485 	if ((vp->v_mount = mp) != NULL)
486 		TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
487 }
488 
489 /*
490  * Create a vnode for a block device.
491  * Used for root filesystem, argdev, and swap areas.
492  * Also used for memory file system special devices.
493  */
494 int
495 bdevvp(dev_t dev, struct vnode **vpp)
496 {
497 	return (getdevvp(dev, vpp, VBLK));
498 }
499 
500 /*
501  * Create a vnode for a character device.
502  * Used for console handling.
503  */
504 int
505 cdevvp(dev_t dev, struct vnode **vpp)
506 {
507 	return (getdevvp(dev, vpp, VCHR));
508 }
509 
510 /*
511  * Create a vnode for a device.
512  * Used by bdevvp (block device) for root file system etc.,
513  * and by cdevvp (character device) for console.
514  */
515 int
516 getdevvp(dev_t dev, struct vnode **vpp, enum vtype type)
517 {
518 	struct vnode *vp;
519 	struct vnode *nvp;
520 	int error;
521 
522 	if (dev == NODEV) {
523 		*vpp = NULLVP;
524 		return (0);
525 	}
526 	error = getnewvnode(VT_NON, NULL, &spec_vops, &nvp);
527 	if (error) {
528 		*vpp = NULLVP;
529 		return (error);
530 	}
531 	vp = nvp;
532 	vp->v_type = type;
533 	if ((nvp = checkalias(vp, dev, NULL)) != 0) {
534 		vput(vp);
535 		vp = nvp;
536 	}
537 	if (vp->v_type == VCHR && cdevsw[major(vp->v_rdev)].d_type == D_TTY)
538 		vp->v_flag |= VISTTY;
539 	*vpp = vp;
540 	return (0);
541 }
542 
543 /*
544  * Check to see if the new vnode represents a special device
545  * for which we already have a vnode (either because of
546  * bdevvp() or because of a different vnode representing
547  * the same block device). If such an alias exists, deallocate
548  * the existing contents and return the aliased vnode. The
549  * caller is responsible for filling it with its new contents.
550  */
551 struct vnode *
552 checkalias(struct vnode *nvp, dev_t nvp_rdev, struct mount *mp)
553 {
554 	struct proc *p = curproc;
555 	struct vnode *vp;
556 	struct vnodechain *vchain;
557 
558 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
559 		return (NULLVP);
560 
561 	vchain = &speclisth[SPECHASH(nvp_rdev)];
562 loop:
563 	SLIST_FOREACH(vp, vchain, v_specnext) {
564 		if (nvp_rdev != vp->v_rdev || nvp->v_type != vp->v_type) {
565 			continue;
566 		}
567 		/*
568 		 * Alias, but not in use, so flush it out.
569 		 */
570 		if (vp->v_usecount == 0) {
571 			vgonel(vp, p);
572 			goto loop;
573 		}
574 		if (vget(vp, LK_EXCLUSIVE)) {
575 			goto loop;
576 		}
577 		break;
578 	}
579 
580 	/*
581 	 * Common case is actually in the if statement
582 	 */
583 	if (vp == NULL || !(vp->v_tag == VT_NON && vp->v_type == VBLK)) {
584 		nvp->v_specinfo = malloc(sizeof(struct specinfo), M_VNODE,
585 			M_WAITOK);
586 		nvp->v_rdev = nvp_rdev;
587 		nvp->v_hashchain = vchain;
588 		nvp->v_specmountpoint = NULL;
589 		nvp->v_speclockf = NULL;
590 		nvp->v_specbitmap = NULL;
591 		if (nvp->v_type == VCHR &&
592 		    (cdevsw[major(nvp_rdev)].d_flags & D_CLONE) &&
593 		    (minor(nvp_rdev) >> CLONE_SHIFT == 0)) {
594 			if (vp != NULLVP)
595 				nvp->v_specbitmap = vp->v_specbitmap;
596 			else
597 				nvp->v_specbitmap = malloc(CLONE_MAPSZ,
598 				    M_VNODE, M_WAITOK | M_ZERO);
599 		}
600 		SLIST_INSERT_HEAD(vchain, nvp, v_specnext);
601 		if (vp != NULLVP) {
602 			nvp->v_flag |= VALIASED;
603 			vp->v_flag |= VALIASED;
604 			vput(vp);
605 		}
606 		return (NULLVP);
607 	}
608 
609 	/*
610 	 * This code is the uncommon case. It is called in case
611 	 * we found an alias that was VT_NON && vtype of VBLK
612 	 * This means we found a block device that was created
613 	 * using bdevvp.
614 	 * An example of such a vnode is the root partition device vnode
615 	 * created in ffs_mountroot.
616 	 *
617 	 * The vnodes created by bdevvp should not be aliased (why?).
618 	 */
619 
620 	VOP_UNLOCK(vp);
621 	vclean(vp, 0, p);
622 	vp->v_op = nvp->v_op;
623 	vp->v_tag = nvp->v_tag;
624 	nvp->v_type = VNON;
625 	insmntque(vp, mp);
626 	return (vp);
627 }
628 
629 /*
630  * Grab a particular vnode from the free list, increment its
631  * reference count and lock it. If the vnode lock bit is set,
632  * the vnode is being eliminated in vgone. In that case, we
633  * cannot grab it, so the process is awakened when the
634  * transition is completed, and an error code is returned to
635  * indicate that the vnode is no longer usable, possibly
636  * having been changed to a new file system type.
637  */
638 int
639 vget(struct vnode *vp, int flags)
640 {
641 	int error, s, onfreelist;
642 
643 	/*
644 	 * If the vnode is in the process of being cleaned out for
645 	 * another use, we wait for the cleaning to finish and then
646 	 * return failure. Cleaning is determined by checking that
647 	 * the VXLOCK flag is set.
648 	 */
649 	mtx_enter(&vnode_mtx);
650 	if (vp->v_lflag & VXLOCK) {
651 		if (flags & LK_NOWAIT) {
652 			mtx_leave(&vnode_mtx);
653 			return (EBUSY);
654 		}
655 
656 		vp->v_lflag |= VXWANT;
657 		msleep_nsec(vp, &vnode_mtx, PINOD, "vget", INFSLP);
658 		mtx_leave(&vnode_mtx);
659 		return (ENOENT);
660 	}
661 	mtx_leave(&vnode_mtx);
662 
663 	onfreelist = vp->v_bioflag & VBIOONFREELIST;
664 	if (vp->v_usecount == 0 && onfreelist) {
665 		s = splbio();
666 		if (vp->v_holdcnt > 0)
667 			TAILQ_REMOVE(&vnode_hold_list, vp, v_freelist);
668 		else
669 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
670 		vp->v_bioflag &= ~VBIOONFREELIST;
671 		splx(s);
672 	}
673 
674 	vp->v_usecount++;
675 	if (flags & LK_TYPE_MASK) {
676 		if ((error = vn_lock(vp, flags)) != 0) {
677 			vp->v_usecount--;
678 			if (vp->v_usecount == 0 && onfreelist)
679 				vputonfreelist(vp);
680 		}
681 		return (error);
682 	}
683 
684 	return (0);
685 }
686 
687 
688 /* Vnode reference. */
689 void
690 vref(struct vnode *vp)
691 {
692 #ifdef DIAGNOSTIC
693 	if (vp->v_usecount == 0)
694 		panic("vref used where vget required");
695 	if (vp->v_type == VNON)
696 		panic("vref on a VNON vnode");
697 #endif
698 	vp->v_usecount++;
699 }
700 
701 void
702 vputonfreelist(struct vnode *vp)
703 {
704 	int s;
705 	struct freelst *lst;
706 
707 	s = splbio();
708 #ifdef DIAGNOSTIC
709 	if (vp->v_usecount != 0)
710 		panic("Use count is not zero!");
711 
712 	/*
713 	 * If the hold count is still positive, one or many threads could still
714 	 * be waiting on the vnode lock inside uvn_io().
715 	 */
716 	if (vp->v_holdcnt == 0 && vp->v_lockcount != 0)
717 		panic("%s: lock count is not zero", __func__);
718 
719 	if (vp->v_bioflag & VBIOONFREELIST) {
720 		vprint("vnode already on free list: ", vp);
721 		panic("vnode already on free list");
722 	}
723 #endif
724 
725 	vp->v_bioflag |= VBIOONFREELIST;
726 	vp->v_bioflag &= ~VBIOERROR;
727 
728 	if (vp->v_holdcnt > 0)
729 		lst = &vnode_hold_list;
730 	else
731 		lst = &vnode_free_list;
732 
733 	if (vp->v_type == VBAD)
734 		TAILQ_INSERT_HEAD(lst, vp, v_freelist);
735 	else
736 		TAILQ_INSERT_TAIL(lst, vp, v_freelist);
737 
738 	splx(s);
739 }
740 
741 /*
742  * vput(), just unlock and vrele()
743  */
744 void
745 vput(struct vnode *vp)
746 {
747 	struct proc *p = curproc;
748 
749 #ifdef DIAGNOSTIC
750 	if (vp == NULL)
751 		panic("vput: null vp");
752 #endif
753 
754 #ifdef DIAGNOSTIC
755 	if (vp->v_usecount == 0) {
756 		vprint("vput: bad ref count", vp);
757 		panic("vput: ref cnt");
758 	}
759 #endif
760 	vp->v_usecount--;
761 	KASSERT(vp->v_usecount > 0 || vp->v_uvcount == 0);
762 	if (vp->v_usecount > 0) {
763 		VOP_UNLOCK(vp);
764 		return;
765 	}
766 
767 #ifdef DIAGNOSTIC
768 	if (vp->v_writecount != 0) {
769 		vprint("vput: bad writecount", vp);
770 		panic("vput: v_writecount != 0");
771 	}
772 #endif
773 
774 	VOP_INACTIVE(vp, p);
775 
776 	if (vp->v_usecount == 0 && !(vp->v_bioflag & VBIOONFREELIST))
777 		vputonfreelist(vp);
778 }
779 
780 /*
781  * Vnode release - use for active VNODES.
782  * If count drops to zero, call inactive routine and return to freelist.
783  * Returns 0 if it did not sleep.
784  */
785 int
786 vrele(struct vnode *vp)
787 {
788 	struct proc *p = curproc;
789 
790 #ifdef DIAGNOSTIC
791 	if (vp == NULL)
792 		panic("vrele: null vp");
793 #endif
794 #ifdef DIAGNOSTIC
795 	if (vp->v_usecount == 0) {
796 		vprint("vrele: bad ref count", vp);
797 		panic("vrele: ref cnt");
798 	}
799 #endif
800 	vp->v_usecount--;
801 	if (vp->v_usecount > 0) {
802 		return (0);
803 	}
804 
805 #ifdef DIAGNOSTIC
806 	if (vp->v_writecount != 0) {
807 		vprint("vrele: bad writecount", vp);
808 		panic("vrele: v_writecount != 0");
809 	}
810 #endif
811 
812 	if (vn_lock(vp, LK_EXCLUSIVE)) {
813 #ifdef DIAGNOSTIC
814 		vprint("vrele: cannot lock", vp);
815 #endif
816 		return (1);
817 	}
818 
819 	VOP_INACTIVE(vp, p);
820 
821 	if (vp->v_usecount == 0 && !(vp->v_bioflag & VBIOONFREELIST))
822 		vputonfreelist(vp);
823 	return (1);
824 }
825 
826 /* Page or buffer structure gets a reference. */
827 void
828 vhold(struct vnode *vp)
829 {
830 	/*
831 	 * If it is on the freelist and the hold count is currently
832 	 * zero, move it to the hold list.
833 	 */
834 	if ((vp->v_bioflag & VBIOONFREELIST) &&
835 	    vp->v_holdcnt == 0 && vp->v_usecount == 0) {
836 		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
837 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
838 	}
839 	vp->v_holdcnt++;
840 }
841 
842 /* Lose interest in a vnode. */
843 void
844 vdrop(struct vnode *vp)
845 {
846 #ifdef DIAGNOSTIC
847 	if (vp->v_holdcnt == 0)
848 		panic("vdrop: zero holdcnt");
849 #endif
850 
851 	vp->v_holdcnt--;
852 
853 	/*
854 	 * If it is on the holdlist and the hold count drops to
855 	 * zero, move it to the free list.
856 	 */
857 	if ((vp->v_bioflag & VBIOONFREELIST) &&
858 	    vp->v_holdcnt == 0 && vp->v_usecount == 0) {
859 		TAILQ_REMOVE(&vnode_hold_list, vp, v_freelist);
860 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
861 	}
862 }
863 
864 /*
865  * Remove any vnodes in the vnode table belonging to mount point mp.
866  *
867  * If MNT_NOFORCE is specified, there should not be any active ones,
868  * return error if any are found (nb: this is a user error, not a
869  * system error). If MNT_FORCE is specified, detach any active vnodes
870  * that are found.
871  */
872 #ifdef DEBUG_SYSCTL
873 int busyprt = 0;	/* print out busy vnodes */
874 struct ctldebug debug_vfs_busyprt = { "vfs_busyprt", &busyprt };
875 #endif
876 
877 int
878 vfs_mount_foreach_vnode(struct mount *mp,
879     int (*func)(struct vnode *, void *), void *arg) {
880 	struct vnode *vp, *nvp;
881 	int error = 0;
882 
883 loop:
884 	TAILQ_FOREACH_SAFE(vp , &mp->mnt_vnodelist, v_mntvnodes, nvp) {
885 		if (vp->v_mount != mp)
886 			goto loop;
887 
888 		error = func(vp, arg);
889 
890 		if (error != 0)
891 			break;
892 	}
893 
894 	return (error);
895 }
896 
897 struct vflush_args {
898 	struct vnode *skipvp;
899 	int busy;
900 	int flags;
901 };
902 
903 int
904 vflush_vnode(struct vnode *vp, void *arg)
905 {
906 	struct vflush_args *va = arg;
907 	struct proc *p = curproc;
908 
909 	if (vp == va->skipvp) {
910 		return (0);
911 	}
912 
913 	if ((va->flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
914 		return (0);
915 	}
916 
917 	/*
918 	 * If WRITECLOSE is set, only flush out regular file
919 	 * vnodes open for writing.
920 	 */
921 	if ((va->flags & WRITECLOSE) &&
922 	    (vp->v_writecount == 0 || vp->v_type != VREG)) {
923 		return (0);
924 	}
925 
926 	/*
927 	 * With v_usecount == 0, all we need to do is clear
928 	 * out the vnode data structures and we are done.
929 	 */
930 	if (vp->v_usecount == 0) {
931 		vgonel(vp, p);
932 		return (0);
933 	}
934 
935 	/*
936 	 * If FORCECLOSE is set, forcibly close the vnode.
937 	 * For block or character devices, revert to an
938 	 * anonymous device. For all other files, just kill them.
939 	 */
940 	if (va->flags & FORCECLOSE) {
941 		if (vp->v_type != VBLK && vp->v_type != VCHR) {
942 			vgonel(vp, p);
943 		} else {
944 			vclean(vp, 0, p);
945 			vp->v_op = &spec_vops;
946 			insmntque(vp, NULL);
947 		}
948 		return (0);
949 	}
950 
951 	/*
952 	 * If set, this is allowed to ignore vnodes which don't
953 	 * have changes pending to disk.
954 	 * XXX Might be nice to check per-fs "inode" flags, but
955 	 * generally the filesystem is sync'd already, right?
956 	 */
957 	if ((va->flags & IGNORECLEAN) &&
958 	    LIST_EMPTY(&vp->v_dirtyblkhd))
959 		return (0);
960 
961 #ifdef DEBUG_SYSCTL
962 	if (busyprt)
963 		vprint("vflush: busy vnode", vp);
964 #endif
965 	va->busy++;
966 	return (0);
967 }
968 
969 int
970 vflush(struct mount *mp, struct vnode *skipvp, int flags)
971 {
972 	struct vflush_args va;
973 	va.skipvp = skipvp;
974 	va.busy = 0;
975 	va.flags = flags;
976 
977 	vfs_mount_foreach_vnode(mp, vflush_vnode, &va);
978 
979 	if (va.busy)
980 		return (EBUSY);
981 	return (0);
982 }
983 
984 /*
985  * Disassociate the underlying file system from a vnode.
986  */
987 void
988 vclean(struct vnode *vp, int flags, struct proc *p)
989 {
990 	int active, do_wakeup = 0;
991 
992 	/*
993 	 * Check to see if the vnode is in use.
994 	 * If so we have to reference it before we clean it out
995 	 * so that its count cannot fall to zero and generate a
996 	 * race against ourselves to recycle it.
997 	 */
998 	if ((active = vp->v_usecount) != 0)
999 		vp->v_usecount++;
1000 
1001 	/*
1002 	 * Prevent the vnode from being recycled or
1003 	 * brought into use while we clean it out.
1004 	 */
1005 	mtx_enter(&vnode_mtx);
1006 	if (vp->v_lflag & VXLOCK)
1007 		panic("vclean: deadlock");
1008 	vp->v_lflag |= VXLOCK;
1009 
1010 	if (vp->v_lockcount > 0) {
1011 		/*
1012 		 * Ensure that any thread currently waiting on the same lock has
1013 		 * observed that the vnode is about to be exclusively locked
1014 		 * before continuing.
1015 		 */
1016 		msleep_nsec(&vp->v_lockcount, &vnode_mtx, PINOD, "vop_lock",
1017 		    INFSLP);
1018 		KASSERT(vp->v_lockcount == 0);
1019 	}
1020 	mtx_leave(&vnode_mtx);
1021 
1022 	/*
1023 	 * Even if the count is zero, the VOP_INACTIVE routine may still
1024 	 * have the object locked while it cleans it out. The VOP_LOCK
1025 	 * ensures that the VOP_INACTIVE routine is done with its work.
1026 	 * For active vnodes, it ensures that no other activity can
1027 	 * occur while the underlying object is being cleaned out.
1028 	 */
1029 	VOP_LOCK(vp, LK_EXCLUSIVE | LK_DRAIN);
1030 
1031 	/*
1032 	 * Clean out any VM data associated with the vnode.
1033 	 */
1034 	uvm_vnp_terminate(vp);
1035 	/*
1036 	 * Clean out any buffers associated with the vnode.
1037 	 */
1038 	if (flags & DOCLOSE)
1039 		vinvalbuf(vp, V_SAVE, NOCRED, p, 0, INFSLP);
1040 	/*
1041 	 * If purging an active vnode, it must be closed and
1042 	 * deactivated before being reclaimed. Note that the
1043 	 * VOP_INACTIVE will unlock the vnode
1044 	 */
1045 	if (active) {
1046 		if (flags & DOCLOSE)
1047 			VOP_CLOSE(vp, FNONBLOCK, NOCRED, p);
1048 		VOP_INACTIVE(vp, p);
1049 	} else {
1050 		/*
1051 		 * Any other processes trying to obtain this lock must first
1052 		 * wait for VXLOCK to clear, then call the new lock operation.
1053 		 */
1054 		VOP_UNLOCK(vp);
1055 	}
1056 
1057 	/*
1058 	 * Reclaim the vnode.
1059 	 */
1060 	if (VOP_RECLAIM(vp, p))
1061 		panic("vclean: cannot reclaim");
1062 	if (active) {
1063 		vp->v_usecount--;
1064 		if (vp->v_usecount == 0) {
1065 			if (vp->v_holdcnt > 0)
1066 				panic("vclean: not clean");
1067 			vputonfreelist(vp);
1068 		}
1069 	}
1070 	cache_purge(vp);
1071 
1072 	/*
1073 	 * Done with purge, notify sleepers of the grim news.
1074 	 */
1075 	vp->v_op = &dead_vops;
1076 	VN_KNOTE(vp, NOTE_REVOKE);
1077 	vp->v_tag = VT_NON;
1078 	mtx_enter(&vnode_mtx);
1079 	vp->v_lflag &= ~VXLOCK;
1080 	if (vp->v_lflag & VXWANT) {
1081 		vp->v_lflag &= ~VXWANT;
1082 		do_wakeup = 1;
1083 	}
1084 	mtx_leave(&vnode_mtx);
1085 	if (do_wakeup)
1086 		wakeup(vp);
1087 }
1088 
1089 /*
1090  * Recycle an unused vnode to the front of the free list.
1091  */
1092 int
1093 vrecycle(struct vnode *vp, struct proc *p)
1094 {
1095 	if (vp->v_usecount == 0) {
1096 		vgonel(vp, p);
1097 		return (1);
1098 	}
1099 	return (0);
1100 }
1101 
1102 /*
1103  * Eliminate all activity associated with a vnode
1104  * in preparation for reuse.
1105  */
1106 void
1107 vgone(struct vnode *vp)
1108 {
1109 	struct proc *p = curproc;
1110 	vgonel(vp, p);
1111 }
1112 
1113 /*
1114  * vgone, with struct proc.
1115  */
1116 void
1117 vgonel(struct vnode *vp, struct proc *p)
1118 {
1119 	struct vnode *vq;
1120 	struct vnode *vx;
1121 
1122 	KASSERT(vp->v_uvcount == 0);
1123 
1124 	/*
1125 	 * If a vgone (or vclean) is already in progress,
1126 	 * wait until it is done and return.
1127 	 */
1128 	mtx_enter(&vnode_mtx);
1129 	if (vp->v_lflag & VXLOCK) {
1130 		vp->v_lflag |= VXWANT;
1131 		msleep_nsec(vp, &vnode_mtx, PINOD, "vgone", INFSLP);
1132 		mtx_leave(&vnode_mtx);
1133 		return;
1134 	}
1135 	mtx_leave(&vnode_mtx);
1136 
1137 	/*
1138 	 * Clean out the filesystem specific data.
1139 	 */
1140 	vclean(vp, DOCLOSE, p);
1141 	/*
1142 	 * Delete from old mount point vnode list, if on one.
1143 	 */
1144 	if (vp->v_mount != NULL)
1145 		insmntque(vp, NULL);
1146 	/*
1147 	 * If special device, remove it from special device alias list
1148 	 * if it is on one.
1149 	 */
1150 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_specinfo != 0) {
1151 		if ((vp->v_flag & VALIASED) == 0 && vp->v_type == VCHR &&
1152 		    (cdevsw[major(vp->v_rdev)].d_flags & D_CLONE) &&
1153 		    (minor(vp->v_rdev) >> CLONE_SHIFT == 0)) {
1154 			free(vp->v_specbitmap, M_VNODE, CLONE_MAPSZ);
1155 		}
1156 		SLIST_REMOVE(vp->v_hashchain, vp, vnode, v_specnext);
1157 		if (vp->v_flag & VALIASED) {
1158 			vx = NULL;
1159 			SLIST_FOREACH(vq, vp->v_hashchain, v_specnext) {
1160 				if (vq->v_rdev != vp->v_rdev ||
1161 				    vq->v_type != vp->v_type)
1162 					continue;
1163 				if (vx)
1164 					break;
1165 				vx = vq;
1166 			}
1167 			if (vx == NULL)
1168 				panic("missing alias");
1169 			if (vq == NULL)
1170 				vx->v_flag &= ~VALIASED;
1171 			vp->v_flag &= ~VALIASED;
1172 		}
1173 		lf_purgelocks(&vp->v_speclockf);
1174 		free(vp->v_specinfo, M_VNODE, sizeof(struct specinfo));
1175 		vp->v_specinfo = NULL;
1176 	}
1177 	/*
1178 	 * If it is on the freelist and not already at the head,
1179 	 * move it to the head of the list.
1180 	 */
1181 	vp->v_type = VBAD;
1182 
1183 	/*
1184 	 * Move onto the free list, unless we were called from
1185 	 * getnewvnode and we're not on any free list
1186 	 */
1187 	if (vp->v_usecount == 0 &&
1188 	    (vp->v_bioflag & VBIOONFREELIST)) {
1189 		int s;
1190 
1191 		s = splbio();
1192 
1193 		if (vp->v_holdcnt > 0)
1194 			panic("vgonel: not clean");
1195 
1196 		if (TAILQ_FIRST(&vnode_free_list) != vp) {
1197 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
1198 			TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
1199 		}
1200 		splx(s);
1201 	}
1202 }
1203 
1204 /*
1205  * Lookup a vnode by device number.
1206  */
1207 int
1208 vfinddev(dev_t dev, enum vtype type, struct vnode **vpp)
1209 {
1210 	struct vnode *vp;
1211 	int rc =0;
1212 
1213 	SLIST_FOREACH(vp, &speclisth[SPECHASH(dev)], v_specnext) {
1214 		if (dev != vp->v_rdev || type != vp->v_type)
1215 			continue;
1216 		*vpp = vp;
1217 		rc = 1;
1218 		break;
1219 	}
1220 	return (rc);
1221 }
1222 
1223 /*
1224  * Revoke all the vnodes corresponding to the specified minor number
1225  * range (endpoints inclusive) of the specified major.
1226  */
1227 void
1228 vdevgone(int maj, int minl, int minh, enum vtype type)
1229 {
1230 	struct vnode *vp;
1231 	int mn;
1232 
1233 	for (mn = minl; mn <= minh; mn++)
1234 		if (vfinddev(makedev(maj, mn), type, &vp))
1235 			VOP_REVOKE(vp, REVOKEALL);
1236 }
1237 
1238 /*
1239  * Calculate the total number of references to a special device.
1240  */
1241 int
1242 vcount(struct vnode *vp)
1243 {
1244 	struct vnode *vq;
1245 	int count;
1246 
1247 loop:
1248 	if ((vp->v_flag & VALIASED) == 0)
1249 		return (vp->v_usecount);
1250 	count = 0;
1251 	SLIST_FOREACH(vq, vp->v_hashchain, v_specnext) {
1252 		if (vq->v_rdev != vp->v_rdev || vq->v_type != vp->v_type)
1253 			continue;
1254 		/*
1255 		 * Alias, but not in use, so flush it out.
1256 		 */
1257 		if (vq->v_usecount == 0 && vq != vp) {
1258 			vgone(vq);
1259 			goto loop;
1260 		}
1261 		count += vq->v_usecount;
1262 	}
1263 	return (count);
1264 }
1265 
1266 #if defined(DEBUG) || defined(DIAGNOSTIC)
1267 /*
1268  * Print out a description of a vnode.
1269  */
1270 static char *typename[] =
1271    { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
1272 
1273 void
1274 vprint(char *label, struct vnode *vp)
1275 {
1276 	char buf[64];
1277 
1278 	if (label != NULL)
1279 		printf("%s: ", label);
1280 	printf("%p, type %s, use %u, write %u, hold %u,",
1281 		vp, typename[vp->v_type], vp->v_usecount, vp->v_writecount,
1282 		vp->v_holdcnt);
1283 	buf[0] = '\0';
1284 	if (vp->v_flag & VROOT)
1285 		strlcat(buf, "|VROOT", sizeof buf);
1286 	if (vp->v_flag & VTEXT)
1287 		strlcat(buf, "|VTEXT", sizeof buf);
1288 	if (vp->v_flag & VSYSTEM)
1289 		strlcat(buf, "|VSYSTEM", sizeof buf);
1290 	if (vp->v_lflag & VXLOCK)
1291 		strlcat(buf, "|VXLOCK", sizeof buf);
1292 	if (vp->v_lflag & VXWANT)
1293 		strlcat(buf, "|VXWANT", sizeof buf);
1294 	if (vp->v_bioflag & VBIOWAIT)
1295 		strlcat(buf, "|VBIOWAIT", sizeof buf);
1296 	if (vp->v_bioflag & VBIOONFREELIST)
1297 		strlcat(buf, "|VBIOONFREELIST", sizeof buf);
1298 	if (vp->v_bioflag & VBIOONSYNCLIST)
1299 		strlcat(buf, "|VBIOONSYNCLIST", sizeof buf);
1300 	if (vp->v_flag & VALIASED)
1301 		strlcat(buf, "|VALIASED", sizeof buf);
1302 	if (buf[0] != '\0')
1303 		printf(" flags (%s)", &buf[1]);
1304 	if (vp->v_data == NULL) {
1305 		printf("\n");
1306 	} else {
1307 		printf("\n\t");
1308 		VOP_PRINT(vp);
1309 	}
1310 }
1311 #endif /* DEBUG || DIAGNOSTIC */
1312 
1313 #ifdef DEBUG
1314 /*
1315  * List all of the locked vnodes in the system.
1316  * Called when debugging the kernel.
1317  */
1318 void
1319 printlockedvnodes(void)
1320 {
1321 	struct mount *mp;
1322 	struct vnode *vp;
1323 
1324 	printf("Locked vnodes\n");
1325 
1326 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1327 		if (vfs_busy(mp, VB_READ|VB_NOWAIT))
1328 			continue;
1329 		TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
1330 			if (VOP_ISLOCKED(vp))
1331 				vprint(NULL, vp);
1332 		}
1333 		vfs_unbusy(mp);
1334 	}
1335 
1336 }
1337 #endif
1338 
1339 /*
1340  * Top level filesystem related information gathering.
1341  */
1342 int
1343 vfs_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
1344     size_t newlen, struct proc *p)
1345 {
1346 	struct vfsconf *vfsp, *tmpvfsp;
1347 	int ret;
1348 
1349 	/* all sysctl names at this level are at least name and field */
1350 	if (namelen < 2)
1351 		return (ENOTDIR);		/* overloaded */
1352 
1353 	if (name[0] != VFS_GENERIC) {
1354 		vfsp = vfs_bytypenum(name[0]);
1355 		if (vfsp == NULL || vfsp->vfc_vfsops->vfs_sysctl == NULL)
1356 			return (EOPNOTSUPP);
1357 
1358 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1359 		    oldp, oldlenp, newp, newlen, p));
1360 	}
1361 
1362 	switch (name[1]) {
1363 	case VFS_MAXTYPENUM:
1364 		return (sysctl_rdint(oldp, oldlenp, newp, maxvfsconf));
1365 
1366 	case VFS_CONF:
1367 		if (namelen < 3)
1368 			return (ENOTDIR);	/* overloaded */
1369 
1370 		vfsp = vfs_bytypenum(name[2]);
1371 		if (vfsp == NULL)
1372 			return (EOPNOTSUPP);
1373 
1374 		/* Make a copy, clear out kernel pointers */
1375 		tmpvfsp = malloc(sizeof(*tmpvfsp), M_TEMP, M_WAITOK|M_ZERO);
1376 		memcpy(tmpvfsp, vfsp, sizeof(*tmpvfsp));
1377 		tmpvfsp->vfc_vfsops = NULL;
1378 
1379 		ret = sysctl_rdstruct(oldp, oldlenp, newp, tmpvfsp,
1380 		    sizeof(struct vfsconf));
1381 
1382 		free(tmpvfsp, M_TEMP, sizeof(*tmpvfsp));
1383 		return (ret);
1384 	case VFS_BCACHESTAT:	/* buffer cache statistics */
1385 		ret = sysctl_rdstruct(oldp, oldlenp, newp, &bcstats,
1386 		    sizeof(struct bcachestats));
1387 		return(ret);
1388 	}
1389 	return (EOPNOTSUPP);
1390 }
1391 
1392 /*
1393  * Check to see if a filesystem is mounted on a block device.
1394  */
1395 int
1396 vfs_mountedon(struct vnode *vp)
1397 {
1398 	struct vnode *vq;
1399 	int error = 0;
1400 
1401 	if (vp->v_specmountpoint != NULL)
1402 		return (EBUSY);
1403 	if (vp->v_flag & VALIASED) {
1404 		SLIST_FOREACH(vq, vp->v_hashchain, v_specnext) {
1405 			if (vq->v_rdev != vp->v_rdev ||
1406 			    vq->v_type != vp->v_type)
1407 				continue;
1408 			if (vq->v_specmountpoint != NULL) {
1409 				error = EBUSY;
1410 				break;
1411 			}
1412 		}
1413 	}
1414 	return (error);
1415 }
1416 
1417 #ifdef NFSSERVER
1418 /*
1419  * Build hash lists of net addresses and hang them off the mount point.
1420  * Called by vfs_export() to set up the lists of export addresses.
1421  */
1422 int
1423 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1424     struct export_args *argp)
1425 {
1426 	struct netcred *np;
1427 	struct radix_node_head *rnh;
1428 	int nplen, i;
1429 	struct radix_node *rn;
1430 	struct sockaddr *saddr, *smask = 0;
1431 	int error;
1432 
1433 	if (argp->ex_addrlen == 0) {
1434 		if (mp->mnt_flag & MNT_DEFEXPORTED)
1435 			return (EPERM);
1436 		np = &nep->ne_defexported;
1437 		/* fill in the kernel's ucred from userspace's xucred */
1438 		if ((error = crfromxucred(&np->netc_anon, &argp->ex_anon)))
1439 			return (error);
1440 		mp->mnt_flag |= MNT_DEFEXPORTED;
1441 		goto finish;
1442 	}
1443 	if (argp->ex_addrlen > MLEN || argp->ex_masklen > MLEN ||
1444 	    argp->ex_addrlen < 0 || argp->ex_masklen < 0)
1445 		return (EINVAL);
1446 	nplen = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1447 	np = (struct netcred *)malloc(nplen, M_NETADDR, M_WAITOK|M_ZERO);
1448 	np->netc_len = nplen;
1449 	saddr = (struct sockaddr *)(np + 1);
1450 	error = copyin(argp->ex_addr, saddr, argp->ex_addrlen);
1451 	if (error)
1452 		goto out;
1453 	if (saddr->sa_len > argp->ex_addrlen)
1454 		saddr->sa_len = argp->ex_addrlen;
1455 	if (argp->ex_masklen) {
1456 		smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1457 		error = copyin(argp->ex_mask, smask, argp->ex_masklen);
1458 		if (error)
1459 			goto out;
1460 		if (smask->sa_len > argp->ex_masklen)
1461 			smask->sa_len = argp->ex_masklen;
1462 	}
1463 	/* fill in the kernel's ucred from userspace's xucred */
1464 	if ((error = crfromxucred(&np->netc_anon, &argp->ex_anon)))
1465 		goto out;
1466 	i = saddr->sa_family;
1467 	switch (i) {
1468 	case AF_INET:
1469 		if ((rnh = nep->ne_rtable_inet) == NULL) {
1470 			if (!rn_inithead((void **)&nep->ne_rtable_inet,
1471 			    offsetof(struct sockaddr_in, sin_addr))) {
1472 				error = ENOBUFS;
1473 				goto out;
1474 			}
1475 			rnh = nep->ne_rtable_inet;
1476 		}
1477 		break;
1478 	default:
1479 		error = EINVAL;
1480 		goto out;
1481 	}
1482 	rn = rn_addroute(saddr, smask, rnh, np->netc_rnodes, 0);
1483 	if (rn == 0 || np != (struct netcred *)rn) { /* already exists */
1484 		error = EPERM;
1485 		goto out;
1486 	}
1487 finish:
1488 	np->netc_exflags = argp->ex_flags;
1489 	return (0);
1490 out:
1491 	free(np, M_NETADDR, np->netc_len);
1492 	return (error);
1493 }
1494 
1495 int
1496 vfs_free_netcred(struct radix_node *rn, void *w, u_int id)
1497 {
1498 	struct radix_node_head *rnh = (struct radix_node_head *)w;
1499 	struct netcred * np = (struct netcred *)rn;
1500 
1501 	rn_delete(rn->rn_key, rn->rn_mask, rnh, NULL);
1502 	free(np, M_NETADDR, np->netc_len);
1503 	return (0);
1504 }
1505 
1506 /*
1507  * Free the net address hash lists that are hanging off the mount points.
1508  */
1509 void
1510 vfs_free_addrlist(struct netexport *nep)
1511 {
1512 	struct radix_node_head *rnh;
1513 
1514 	if ((rnh = nep->ne_rtable_inet) != NULL) {
1515 		rn_walktree(rnh, vfs_free_netcred, rnh);
1516 		free(rnh, M_RTABLE, sizeof(*rnh));
1517 		nep->ne_rtable_inet = NULL;
1518 	}
1519 }
1520 #endif /* NFSSERVER */
1521 
1522 int
1523 vfs_export(struct mount *mp, struct netexport *nep, struct export_args *argp)
1524 {
1525 #ifdef NFSSERVER
1526 	int error;
1527 
1528 	if (argp->ex_flags & MNT_DELEXPORT) {
1529 		vfs_free_addrlist(nep);
1530 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1531 	}
1532 	if (argp->ex_flags & MNT_EXPORTED) {
1533 		if ((error = vfs_hang_addrlist(mp, nep, argp)) != 0)
1534 			return (error);
1535 		mp->mnt_flag |= MNT_EXPORTED;
1536 	}
1537 	return (0);
1538 #else
1539 	return (ENOTSUP);
1540 #endif /* NFSSERVER */
1541 }
1542 
1543 struct netcred *
1544 vfs_export_lookup(struct mount *mp, struct netexport *nep, struct mbuf *nam)
1545 {
1546 #ifdef NFSSERVER
1547 	struct netcred *np;
1548 	struct radix_node_head *rnh;
1549 	struct sockaddr *saddr;
1550 
1551 	np = NULL;
1552 	if (mp->mnt_flag & MNT_EXPORTED) {
1553 		/*
1554 		 * Lookup in the export list first.
1555 		 */
1556 		if (nam != NULL) {
1557 			saddr = mtod(nam, struct sockaddr *);
1558 			switch(saddr->sa_family) {
1559 			case AF_INET:
1560 				rnh = nep->ne_rtable_inet;
1561 				break;
1562 			default:
1563 				rnh = NULL;
1564 				break;
1565 			}
1566 			if (rnh != NULL)
1567 				np = (struct netcred *)rn_match(saddr, rnh);
1568 		}
1569 		/*
1570 		 * If no address match, use the default if it exists.
1571 		 */
1572 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
1573 			np = &nep->ne_defexported;
1574 	}
1575 	return (np);
1576 #else
1577 	return (NULL);
1578 #endif /* NFSSERVER */
1579 }
1580 
1581 /*
1582  * Do the usual access checking.
1583  * file_mode, uid and gid are from the vnode in question,
1584  * while acc_mode and cred are from the VOP_ACCESS parameter list
1585  */
1586 int
1587 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1588     mode_t acc_mode, struct ucred *cred)
1589 {
1590 	mode_t mask;
1591 
1592 	/* User id 0 always gets read/write access. */
1593 	if (cred->cr_uid == 0) {
1594 		/* For VEXEC, at least one of the execute bits must be set. */
1595 		if ((acc_mode & VEXEC) && type != VDIR &&
1596 		    (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1597 			return EACCES;
1598 		return 0;
1599 	}
1600 
1601 	mask = 0;
1602 
1603 	/* Otherwise, check the owner. */
1604 	if (cred->cr_uid == uid) {
1605 		if (acc_mode & VEXEC)
1606 			mask |= S_IXUSR;
1607 		if (acc_mode & VREAD)
1608 			mask |= S_IRUSR;
1609 		if (acc_mode & VWRITE)
1610 			mask |= S_IWUSR;
1611 		return (file_mode & mask) == mask ? 0 : EACCES;
1612 	}
1613 
1614 	/* Otherwise, check the groups. */
1615 	if (groupmember(gid, cred)) {
1616 		if (acc_mode & VEXEC)
1617 			mask |= S_IXGRP;
1618 		if (acc_mode & VREAD)
1619 			mask |= S_IRGRP;
1620 		if (acc_mode & VWRITE)
1621 			mask |= S_IWGRP;
1622 		return (file_mode & mask) == mask ? 0 : EACCES;
1623 	}
1624 
1625 	/* Otherwise, check everyone else. */
1626 	if (acc_mode & VEXEC)
1627 		mask |= S_IXOTH;
1628 	if (acc_mode & VREAD)
1629 		mask |= S_IROTH;
1630 	if (acc_mode & VWRITE)
1631 		mask |= S_IWOTH;
1632 	return (file_mode & mask) == mask ? 0 : EACCES;
1633 }
1634 
1635 int
1636 vnoperm(struct vnode *vp)
1637 {
1638 	if (vp->v_flag & VROOT || vp->v_mount == NULL)
1639 		return 0;
1640 
1641 	return (vp->v_mount->mnt_flag & MNT_NOPERM);
1642 }
1643 
1644 struct rwlock vfs_stall_lock = RWLOCK_INITIALIZER("vfs_stall");
1645 unsigned int vfs_stalling = 0;
1646 
1647 int
1648 vfs_stall(struct proc *p, int stall)
1649 {
1650 	struct mount *mp;
1651 	int allerror = 0, error;
1652 
1653 	if (stall) {
1654 		atomic_inc_int(&vfs_stalling);
1655 		rw_enter_write(&vfs_stall_lock);
1656 	}
1657 
1658 	/*
1659 	 * The loop variable mp is protected by vfs_busy() so that it cannot
1660 	 * be unmounted while VFS_SYNC() sleeps.  Traverse forward to keep the
1661 	 * lock order consistent with dounmount().
1662 	 */
1663 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1664 		if (stall) {
1665 			error = vfs_busy(mp, VB_WRITE|VB_WAIT|VB_DUPOK);
1666 			if (error) {
1667 				printf("%s: busy\n", mp->mnt_stat.f_mntonname);
1668 				allerror = error;
1669 				continue;
1670 			}
1671 			uvm_vnp_sync(mp);
1672 			error = VFS_SYNC(mp, MNT_WAIT, stall, p->p_ucred, p);
1673 			if (error) {
1674 				printf("%s: failed to sync\n",
1675 				    mp->mnt_stat.f_mntonname);
1676 				vfs_unbusy(mp);
1677 				allerror = error;
1678 				continue;
1679 			}
1680 			mp->mnt_flag |= MNT_STALLED;
1681 		} else {
1682 			if (mp->mnt_flag & MNT_STALLED) {
1683 				vfs_unbusy(mp);
1684 				mp->mnt_flag &= ~MNT_STALLED;
1685 			}
1686 		}
1687 	}
1688 
1689 	if (!stall) {
1690 		rw_exit_write(&vfs_stall_lock);
1691 		atomic_dec_int(&vfs_stalling);
1692 	}
1693 
1694 	return (allerror);
1695 }
1696 
1697 void
1698 vfs_stall_barrier(void)
1699 {
1700 	if (__predict_false(vfs_stalling)) {
1701 		rw_enter_read(&vfs_stall_lock);
1702 		rw_exit_read(&vfs_stall_lock);
1703 	}
1704 }
1705 
1706 /*
1707  * Unmount all file systems.
1708  * We traverse the list in reverse order under the assumption that doing so
1709  * will avoid needing to worry about dependencies.
1710  */
1711 void
1712 vfs_unmountall(void)
1713 {
1714 	struct mount *mp, *nmp;
1715 	int allerror, error, again = 1;
1716 
1717  retry:
1718 	allerror = 0;
1719 	TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, nmp) {
1720 		if (vfs_busy(mp, VB_WRITE|VB_NOWAIT))
1721 			continue;
1722 		/* XXX Here is a race, the next pointer is not locked. */
1723 		if ((error = dounmount(mp, MNT_FORCE, curproc)) != 0) {
1724 			printf("unmount of %s failed with error %d\n",
1725 			    mp->mnt_stat.f_mntonname, error);
1726 			allerror = 1;
1727 		}
1728 	}
1729 
1730 	if (allerror) {
1731 		printf("WARNING: some file systems would not unmount\n");
1732 		if (again) {
1733 			printf("retrying\n");
1734 			again = 0;
1735 			goto retry;
1736 		}
1737 	}
1738 }
1739 
1740 /*
1741  * Sync and unmount file systems before shutting down.
1742  */
1743 void
1744 vfs_shutdown(struct proc *p)
1745 {
1746 #ifdef ACCOUNTING
1747 	acct_shutdown();
1748 #endif
1749 
1750 	printf("syncing disks...");
1751 
1752 	if (panicstr == 0) {
1753 		/* Sync before unmount, in case we hang on something. */
1754 		sys_sync(p, NULL, NULL);
1755 		vfs_unmountall();
1756 	}
1757 
1758 #if NSOFTRAID > 0
1759 	sr_quiesce();
1760 #endif
1761 
1762 	if (vfs_syncwait(p, 1))
1763 		printf(" giving up\n");
1764 	else
1765 		printf(" done\n");
1766 }
1767 
1768 /*
1769  * perform sync() operation and wait for buffers to flush.
1770  */
1771 int
1772 vfs_syncwait(struct proc *p, int verbose)
1773 {
1774 	struct buf *bp;
1775 	int iter, nbusy, dcount, s;
1776 #ifdef MULTIPROCESSOR
1777 	int hold_count;
1778 #endif
1779 
1780 	sys_sync(p, NULL, NULL);
1781 
1782 	/* Wait for sync to finish. */
1783 	dcount = 10000;
1784 	for (iter = 0; iter < 20; iter++) {
1785 		nbusy = 0;
1786 		LIST_FOREACH(bp, &bufhead, b_list) {
1787 			if ((bp->b_flags & (B_BUSY|B_INVAL|B_READ)) == B_BUSY)
1788 				nbusy++;
1789 			/*
1790 			 * With soft updates, some buffers that are
1791 			 * written will be remarked as dirty until other
1792 			 * buffers are written.
1793 			 */
1794 			if (bp->b_flags & B_DELWRI) {
1795 				s = splbio();
1796 				bremfree(bp);
1797 				buf_acquire(bp);
1798 				splx(s);
1799 				nbusy++;
1800 				bawrite(bp);
1801 				if (dcount-- <= 0) {
1802 					if (verbose)
1803 						printf("softdep ");
1804 					return 1;
1805 				}
1806 			}
1807 		}
1808 		if (nbusy == 0)
1809 			break;
1810 		if (verbose)
1811 			printf("%d ", nbusy);
1812 #ifdef MULTIPROCESSOR
1813 		if (_kernel_lock_held())
1814 			hold_count = __mp_release_all(&kernel_lock);
1815 		else
1816 			hold_count = 0;
1817 #endif
1818 		DELAY(40000 * iter);
1819 #ifdef MULTIPROCESSOR
1820 		if (hold_count)
1821 			__mp_acquire_count(&kernel_lock, hold_count);
1822 #endif
1823 	}
1824 
1825 	return nbusy;
1826 }
1827 
1828 /*
1829  * posix file system related system variables.
1830  */
1831 int
1832 fs_posix_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
1833     void *newp, size_t newlen, struct proc *p)
1834 {
1835 	/* all sysctl names at this level are terminal */
1836 	if (namelen != 1)
1837 		return (ENOTDIR);
1838 
1839 	switch (name[0]) {
1840 	case FS_POSIX_SETUID:
1841 		if (newp && securelevel > 0)
1842 			return (EPERM);
1843 		return(sysctl_int(oldp, oldlenp, newp, newlen, &suid_clear));
1844 	default:
1845 		return (EOPNOTSUPP);
1846 	}
1847 	/* NOTREACHED */
1848 }
1849 
1850 /*
1851  * file system related system variables.
1852  */
1853 int
1854 fs_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
1855     size_t newlen, struct proc *p)
1856 {
1857 	sysctlfn *fn;
1858 
1859 	switch (name[0]) {
1860 	case FS_POSIX:
1861 		fn = fs_posix_sysctl;
1862 		break;
1863 	default:
1864 		return (EOPNOTSUPP);
1865 	}
1866 	return (*fn)(name + 1, namelen - 1, oldp, oldlenp, newp, newlen, p);
1867 }
1868 
1869 
1870 /*
1871  * Routines dealing with vnodes and buffers
1872  */
1873 
1874 /*
1875  * Wait for all outstanding I/Os to complete
1876  *
1877  * Manipulates v_numoutput. Must be called at splbio()
1878  */
1879 int
1880 vwaitforio(struct vnode *vp, int slpflag, char *wmesg, uint64_t timeo)
1881 {
1882 	int error = 0;
1883 
1884 	splassert(IPL_BIO);
1885 
1886 	while (vp->v_numoutput) {
1887 		vp->v_bioflag |= VBIOWAIT;
1888 		error = tsleep_nsec(&vp->v_numoutput,
1889 		    slpflag | (PRIBIO + 1), wmesg, timeo);
1890 		if (error)
1891 			break;
1892 	}
1893 
1894 	return (error);
1895 }
1896 
1897 /*
1898  * Update outstanding I/O count and do wakeup if requested.
1899  *
1900  * Manipulates v_numoutput. Must be called at splbio()
1901  */
1902 void
1903 vwakeup(struct vnode *vp)
1904 {
1905 	splassert(IPL_BIO);
1906 
1907 	if (vp != NULL) {
1908 		if (vp->v_numoutput-- == 0)
1909 			panic("vwakeup: neg numoutput");
1910 		if ((vp->v_bioflag & VBIOWAIT) && vp->v_numoutput == 0) {
1911 			vp->v_bioflag &= ~VBIOWAIT;
1912 			wakeup(&vp->v_numoutput);
1913 		}
1914 	}
1915 }
1916 
1917 /*
1918  * Flush out and invalidate all buffers associated with a vnode.
1919  * Called with the underlying object locked.
1920  */
1921 int
1922 vinvalbuf(struct vnode *vp, int flags, struct ucred *cred, struct proc *p,
1923     int slpflag, uint64_t slptimeo)
1924 {
1925 	struct buf *bp;
1926 	struct buf *nbp, *blist;
1927 	int s, error;
1928 
1929 #ifdef VFSLCKDEBUG
1930 	if ((vp->v_op->vop_islocked != nullop) && !VOP_ISLOCKED(vp))
1931 		panic("%s: vp isn't locked, vp %p", __func__, vp);
1932 #endif
1933 
1934 	if (flags & V_SAVE) {
1935 		s = splbio();
1936 		vwaitforio(vp, 0, "vinvalbuf", INFSLP);
1937 		if (!LIST_EMPTY(&vp->v_dirtyblkhd)) {
1938 			splx(s);
1939 			if ((error = VOP_FSYNC(vp, cred, MNT_WAIT, p)) != 0)
1940 				return (error);
1941 			s = splbio();
1942 			if (vp->v_numoutput > 0 ||
1943 			    !LIST_EMPTY(&vp->v_dirtyblkhd))
1944 				panic("%s: dirty bufs, vp %p", __func__, vp);
1945 		}
1946 		splx(s);
1947 	}
1948 loop:
1949 	s = splbio();
1950 	for (;;) {
1951 		int count = 0;
1952 		if ((blist = LIST_FIRST(&vp->v_cleanblkhd)) &&
1953 		    (flags & V_SAVEMETA))
1954 			while (blist && blist->b_lblkno < 0)
1955 				blist = LIST_NEXT(blist, b_vnbufs);
1956 		if (blist == NULL &&
1957 		    (blist = LIST_FIRST(&vp->v_dirtyblkhd)) &&
1958 		    (flags & V_SAVEMETA))
1959 			while (blist && blist->b_lblkno < 0)
1960 				blist = LIST_NEXT(blist, b_vnbufs);
1961 		if (!blist)
1962 			break;
1963 
1964 		for (bp = blist; bp; bp = nbp) {
1965 			nbp = LIST_NEXT(bp, b_vnbufs);
1966 			if (flags & V_SAVEMETA && bp->b_lblkno < 0)
1967 				continue;
1968 			if (bp->b_flags & B_BUSY) {
1969 				bp->b_flags |= B_WANTED;
1970 				error = tsleep_nsec(bp, slpflag | (PRIBIO + 1),
1971 				    "vinvalbuf", slptimeo);
1972 				if (error) {
1973 					splx(s);
1974 					return (error);
1975 				}
1976 				break;
1977 			}
1978 			bremfree(bp);
1979 			/*
1980 			 * XXX Since there are no node locks for NFS, I believe
1981 			 * there is a slight chance that a delayed write will
1982 			 * occur while sleeping just above, so check for it.
1983 			 */
1984 			if ((bp->b_flags & B_DELWRI) && (flags & V_SAVE)) {
1985 				buf_acquire(bp);
1986 				splx(s);
1987 				(void) VOP_BWRITE(bp);
1988 				goto loop;
1989 			}
1990 			buf_acquire_nomap(bp);
1991 			bp->b_flags |= B_INVAL;
1992 			brelse(bp);
1993 			count++;
1994 			/*
1995 			 * XXX Temporary workaround XXX
1996 			 *
1997 			 * If this is a gigantisch vnode and we are
1998 			 * trashing a ton of buffers, drop the lock
1999 			 * and yield every so often. The longer term
2000 			 * fix is to add a separate list for these
2001 			 * invalid buffers so we don't have to do the
2002 			 * work to free these here.
2003 			 */
2004 			if (count > 100) {
2005 				splx(s);
2006 				sched_pause(yield);
2007 				goto loop;
2008 			}
2009 		}
2010 	}
2011 	if (!(flags & V_SAVEMETA) &&
2012 	    (!LIST_EMPTY(&vp->v_dirtyblkhd) || !LIST_EMPTY(&vp->v_cleanblkhd)))
2013 		panic("%s: flush failed, vp %p", __func__, vp);
2014 	splx(s);
2015 	return (0);
2016 }
2017 
2018 void
2019 vflushbuf(struct vnode *vp, int sync)
2020 {
2021 	struct buf *bp, *nbp;
2022 	int s;
2023 
2024 loop:
2025 	s = splbio();
2026 	LIST_FOREACH_SAFE(bp, &vp->v_dirtyblkhd, b_vnbufs, nbp) {
2027 		if ((bp->b_flags & B_BUSY))
2028 			continue;
2029 		if ((bp->b_flags & B_DELWRI) == 0)
2030 			panic("vflushbuf: not dirty");
2031 		bremfree(bp);
2032 		buf_acquire(bp);
2033 		splx(s);
2034 		/*
2035 		 * Wait for I/O associated with indirect blocks to complete,
2036 		 * since there is no way to quickly wait for them below.
2037 		 */
2038 		if (bp->b_vp == vp || sync == 0)
2039 			(void) bawrite(bp);
2040 		else
2041 			(void) bwrite(bp);
2042 		goto loop;
2043 	}
2044 	if (sync == 0) {
2045 		splx(s);
2046 		return;
2047 	}
2048 	vwaitforio(vp, 0, "vflushbuf", INFSLP);
2049 	if (!LIST_EMPTY(&vp->v_dirtyblkhd)) {
2050 		splx(s);
2051 #ifdef DIAGNOSTIC
2052 		vprint("vflushbuf: dirty", vp);
2053 #endif
2054 		goto loop;
2055 	}
2056 	splx(s);
2057 }
2058 
2059 /*
2060  * Associate a buffer with a vnode.
2061  *
2062  * Manipulates buffer vnode queues. Must be called at splbio().
2063  */
2064 void
2065 bgetvp(struct vnode *vp, struct buf *bp)
2066 {
2067 	splassert(IPL_BIO);
2068 
2069 
2070 	if (bp->b_vp)
2071 		panic("bgetvp: not free");
2072 	vhold(vp);
2073 	bp->b_vp = vp;
2074 	if (vp->v_type == VBLK || vp->v_type == VCHR)
2075 		bp->b_dev = vp->v_rdev;
2076 	else
2077 		bp->b_dev = NODEV;
2078 	/*
2079 	 * Insert onto list for new vnode.
2080 	 */
2081 	bufinsvn(bp, &vp->v_cleanblkhd);
2082 }
2083 
2084 /*
2085  * Disassociate a buffer from a vnode.
2086  *
2087  * Manipulates vnode buffer queues. Must be called at splbio().
2088  */
2089 void
2090 brelvp(struct buf *bp)
2091 {
2092 	struct vnode *vp;
2093 
2094 	splassert(IPL_BIO);
2095 
2096 	if ((vp = bp->b_vp) == (struct vnode *) 0)
2097 		panic("brelvp: NULL");
2098 	/*
2099 	 * Delete from old vnode list, if on one.
2100 	 */
2101 	if (LIST_NEXT(bp, b_vnbufs) != NOLIST)
2102 		bufremvn(bp);
2103 	if ((vp->v_bioflag & VBIOONSYNCLIST) &&
2104 	    LIST_EMPTY(&vp->v_dirtyblkhd)) {
2105 		vp->v_bioflag &= ~VBIOONSYNCLIST;
2106 		LIST_REMOVE(vp, v_synclist);
2107 	}
2108 	bp->b_vp = NULL;
2109 
2110 	vdrop(vp);
2111 }
2112 
2113 /*
2114  * Replaces the current vnode associated with the buffer, if any,
2115  * with a new vnode.
2116  *
2117  * If an output I/O is pending on the buffer, the old vnode
2118  * I/O count is adjusted.
2119  *
2120  * Ignores vnode buffer queues. Must be called at splbio().
2121  */
2122 void
2123 buf_replacevnode(struct buf *bp, struct vnode *newvp)
2124 {
2125 	struct vnode *oldvp = bp->b_vp;
2126 
2127 	splassert(IPL_BIO);
2128 
2129 	if (oldvp)
2130 		brelvp(bp);
2131 
2132 	if ((bp->b_flags & (B_READ | B_DONE)) == 0) {
2133 		newvp->v_numoutput++;	/* put it on swapdev */
2134 		vwakeup(oldvp);
2135 	}
2136 
2137 	bgetvp(newvp, bp);
2138 	bufremvn(bp);
2139 }
2140 
2141 /*
2142  * Used to assign buffers to the appropriate clean or dirty list on
2143  * the vnode and to add newly dirty vnodes to the appropriate
2144  * filesystem syncer list.
2145  *
2146  * Manipulates vnode buffer queues. Must be called at splbio().
2147  */
2148 void
2149 reassignbuf(struct buf *bp)
2150 {
2151 	struct buflists *listheadp;
2152 	int delay;
2153 	struct vnode *vp = bp->b_vp;
2154 
2155 	splassert(IPL_BIO);
2156 
2157 	/*
2158 	 * Delete from old vnode list, if on one.
2159 	 */
2160 	if (LIST_NEXT(bp, b_vnbufs) != NOLIST)
2161 		bufremvn(bp);
2162 
2163 	/*
2164 	 * If dirty, put on list of dirty buffers;
2165 	 * otherwise insert onto list of clean buffers.
2166 	 */
2167 	if ((bp->b_flags & B_DELWRI) == 0) {
2168 		listheadp = &vp->v_cleanblkhd;
2169 		if ((vp->v_bioflag & VBIOONSYNCLIST) &&
2170 		    LIST_EMPTY(&vp->v_dirtyblkhd)) {
2171 			vp->v_bioflag &= ~VBIOONSYNCLIST;
2172 			LIST_REMOVE(vp, v_synclist);
2173 		}
2174 	} else {
2175 		listheadp = &vp->v_dirtyblkhd;
2176 		if ((vp->v_bioflag & VBIOONSYNCLIST) == 0) {
2177 			switch (vp->v_type) {
2178 			case VDIR:
2179 				delay = syncdelay / 2;
2180 				break;
2181 			case VBLK:
2182 				if (vp->v_specmountpoint != NULL) {
2183 					delay = syncdelay / 3;
2184 					break;
2185 				}
2186 				/* FALLTHROUGH */
2187 			default:
2188 				delay = syncdelay;
2189 			}
2190 			vn_syncer_add_to_worklist(vp, delay);
2191 		}
2192 	}
2193 	bufinsvn(bp, listheadp);
2194 }
2195 
2196 /*
2197  * Check if vnode represents a disk device
2198  */
2199 int
2200 vn_isdisk(struct vnode *vp, int *errp)
2201 {
2202 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2203 		return (0);
2204 
2205 	return (1);
2206 }
2207 
2208 #ifdef DDB
2209 #include <machine/db_machdep.h>
2210 #include <ddb/db_interface.h>
2211 
2212 void
2213 vfs_buf_print(void *b, int full,
2214     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
2215 {
2216 	struct buf *bp = b;
2217 
2218 	(*pr)("  vp %p lblkno 0x%llx blkno 0x%llx dev 0x%x\n"
2219 	      "  proc %p error %d flags %lb\n",
2220 	    bp->b_vp, (int64_t)bp->b_lblkno, (int64_t)bp->b_blkno, bp->b_dev,
2221 	    bp->b_proc, bp->b_error, bp->b_flags, B_BITS);
2222 
2223 	(*pr)("  bufsize 0x%lx bcount 0x%lx resid 0x%lx\n"
2224 	      "  data %p saveaddr %p dep %p iodone %p\n",
2225 	    bp->b_bufsize, bp->b_bcount, (long)bp->b_resid,
2226 	    bp->b_data, bp->b_saveaddr,
2227 	    LIST_FIRST(&bp->b_dep), bp->b_iodone);
2228 
2229 	(*pr)("  dirty {off 0x%x end 0x%x} valid {off 0x%x end 0x%x}\n",
2230 	    bp->b_dirtyoff, bp->b_dirtyend, bp->b_validoff, bp->b_validend);
2231 
2232 #ifdef FFS_SOFTUPDATES
2233 	if (full)
2234 		softdep_print(bp, full, pr);
2235 #endif
2236 }
2237 
2238 const char *vtypes[] = { VTYPE_NAMES };
2239 const char *vtags[] = { VTAG_NAMES };
2240 
2241 void
2242 vfs_vnode_print(void *v, int full,
2243     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
2244 {
2245 	struct vnode *vp = v;
2246 
2247 	(*pr)("tag %s(%d) type %s(%d) mount %p typedata %p\n",
2248 	      (u_int)vp->v_tag >= nitems(vtags)? "<unk>":vtags[vp->v_tag],
2249 	      vp->v_tag,
2250 	      (u_int)vp->v_type >= nitems(vtypes)? "<unk>":vtypes[vp->v_type],
2251 	      vp->v_type, vp->v_mount, vp->v_mountedhere);
2252 
2253 	(*pr)("data %p usecount %d writecount %d holdcnt %d numoutput %d\n",
2254 	      vp->v_data, vp->v_usecount, vp->v_writecount,
2255 	      vp->v_holdcnt, vp->v_numoutput);
2256 
2257 	/* uvm_object_printit(&vp->v_uobj, full, pr); */
2258 
2259 	if (full) {
2260 		struct buf *bp;
2261 
2262 		(*pr)("clean bufs:\n");
2263 		LIST_FOREACH(bp, &vp->v_cleanblkhd, b_vnbufs) {
2264 			(*pr)(" bp %p\n", bp);
2265 			vfs_buf_print(bp, full, pr);
2266 		}
2267 
2268 		(*pr)("dirty bufs:\n");
2269 		LIST_FOREACH(bp, &vp->v_dirtyblkhd, b_vnbufs) {
2270 			(*pr)(" bp %p\n", bp);
2271 			vfs_buf_print(bp, full, pr);
2272 		}
2273 	}
2274 }
2275 
2276 void
2277 vfs_mount_print(struct mount *mp, int full,
2278     int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2))))
2279 {
2280 	struct vfsconf *vfc = mp->mnt_vfc;
2281 	struct vnode *vp;
2282 	int cnt;
2283 
2284 	(*pr)("flags %b\nvnodecovered %p syncer %p data %p\n",
2285 	    mp->mnt_flag, MNT_BITS,
2286 	    mp->mnt_vnodecovered, mp->mnt_syncer, mp->mnt_data);
2287 
2288 	(*pr)("vfsconf: ops %p name \"%s\" num %d ref %u flags 0x%x\n",
2289 	    vfc->vfc_vfsops, vfc->vfc_name, vfc->vfc_typenum,
2290 	    vfc->vfc_refcount, vfc->vfc_flags);
2291 
2292 	(*pr)("statvfs cache: bsize %x iosize %x\n"
2293 	    "blocks %llu free %llu avail %lld\n",
2294 	    mp->mnt_stat.f_bsize, mp->mnt_stat.f_iosize, mp->mnt_stat.f_blocks,
2295 	    mp->mnt_stat.f_bfree, mp->mnt_stat.f_bavail);
2296 
2297 	(*pr)("  files %llu ffiles %llu favail %lld\n", mp->mnt_stat.f_files,
2298 	    mp->mnt_stat.f_ffree, mp->mnt_stat.f_favail);
2299 
2300 	(*pr)("  f_fsidx {0x%x, 0x%x} owner %u ctime 0x%llx\n",
2301 	    mp->mnt_stat.f_fsid.val[0], mp->mnt_stat.f_fsid.val[1],
2302 	    mp->mnt_stat.f_owner, mp->mnt_stat.f_ctime);
2303 
2304 	(*pr)("  syncwrites %llu asyncwrites = %llu\n",
2305 	    mp->mnt_stat.f_syncwrites, mp->mnt_stat.f_asyncwrites);
2306 
2307 	(*pr)("  syncreads %llu asyncreads = %llu\n",
2308 	    mp->mnt_stat.f_syncreads, mp->mnt_stat.f_asyncreads);
2309 
2310 	(*pr)("  fstype \"%s\" mnton \"%s\" mntfrom \"%s\" mntspec \"%s\"\n",
2311 	    mp->mnt_stat.f_fstypename, mp->mnt_stat.f_mntonname,
2312 	    mp->mnt_stat.f_mntfromname, mp->mnt_stat.f_mntfromspec);
2313 
2314 	(*pr)("locked vnodes:");
2315 	/* XXX would take mountlist lock, except ddb has no context */
2316 	cnt = 0;
2317 	TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
2318 		if (VOP_ISLOCKED(vp)) {
2319 			if (cnt == 0)
2320 				(*pr)("\n  %p", vp);
2321 			else if ((cnt % (72 / (sizeof(void *) * 2 + 4))) == 0)
2322 				(*pr)(",\n  %p", vp);
2323 			else
2324 				(*pr)(", %p", vp);
2325 			cnt++;
2326 		}
2327 	}
2328 	(*pr)("\n");
2329 
2330 	if (full) {
2331 		(*pr)("all vnodes:");
2332 		/* XXX would take mountlist lock, except ddb has no context */
2333 		cnt = 0;
2334 		TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
2335 			if (cnt == 0)
2336 				(*pr)("\n  %p", vp);
2337 			else if ((cnt % (72 / (sizeof(void *) * 2 + 4))) == 0)
2338 				(*pr)(",\n  %p", vp);
2339 			else
2340 				(*pr)(", %p", vp);
2341 			cnt++;
2342 		}
2343 		(*pr)("\n");
2344 	}
2345 }
2346 #endif /* DDB */
2347 
2348 void
2349 copy_statfs_info(struct statfs *sbp, const struct mount *mp)
2350 {
2351 	const struct statfs *mbp;
2352 
2353 	strncpy(sbp->f_fstypename, mp->mnt_vfc->vfc_name, MFSNAMELEN);
2354 
2355 	if (sbp == (mbp = &mp->mnt_stat))
2356 		return;
2357 
2358 	sbp->f_fsid = mbp->f_fsid;
2359 	sbp->f_owner = mbp->f_owner;
2360 	sbp->f_flags = mbp->f_flags;
2361 	sbp->f_syncwrites = mbp->f_syncwrites;
2362 	sbp->f_asyncwrites = mbp->f_asyncwrites;
2363 	sbp->f_syncreads = mbp->f_syncreads;
2364 	sbp->f_asyncreads = mbp->f_asyncreads;
2365 	sbp->f_namemax = mbp->f_namemax;
2366 	memcpy(sbp->f_mntonname, mp->mnt_stat.f_mntonname, MNAMELEN);
2367 	memcpy(sbp->f_mntfromname, mp->mnt_stat.f_mntfromname, MNAMELEN);
2368 	memcpy(sbp->f_mntfromspec, mp->mnt_stat.f_mntfromspec, MNAMELEN);
2369 	memcpy(&sbp->mount_info, &mp->mnt_stat.mount_info,
2370 	    sizeof(union mount_info));
2371 }
2372