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