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