xref: /dragonfly/sys/kern/vfs_subr.c (revision 984263bc)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
39  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
40  */
41 
42 /*
43  * External virtual filesystem routines
44  */
45 #include "opt_ddb.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/buf.h>
50 #include <sys/conf.h>
51 #include <sys/dirent.h>
52 #include <sys/domain.h>
53 #include <sys/eventhandler.h>
54 #include <sys/fcntl.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/malloc.h>
58 #include <sys/mbuf.h>
59 #include <sys/mount.h>
60 #include <sys/namei.h>
61 #include <sys/proc.h>
62 #include <sys/reboot.h>
63 #include <sys/socket.h>
64 #include <sys/stat.h>
65 #include <sys/sysctl.h>
66 #include <sys/syslog.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
69 
70 #include <machine/limits.h>
71 
72 #include <vm/vm.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_extern.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vnode_pager.h>
80 #include <vm/vm_zone.h>
81 
82 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
83 
84 static void	insmntque __P((struct vnode *vp, struct mount *mp));
85 static void	vclean __P((struct vnode *vp, int flags, struct proc *p));
86 static unsigned long	numvnodes;
87 static void	vlruvp(struct vnode *vp);
88 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
89 
90 enum vtype iftovt_tab[16] = {
91 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
92 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
93 };
94 int vttoif_tab[9] = {
95 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
96 	S_IFSOCK, S_IFIFO, S_IFMT,
97 };
98 
99 static TAILQ_HEAD(freelst, vnode) vnode_free_list;	/* vnode free list */
100 
101 static u_long wantfreevnodes = 25;
102 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
103 static u_long freevnodes = 0;
104 SYSCTL_INT(_debug, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
105 
106 static int reassignbufcalls;
107 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
108 static int reassignbufloops;
109 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW, &reassignbufloops, 0, "");
110 static int reassignbufsortgood;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW, &reassignbufsortgood, 0, "");
112 static int reassignbufsortbad;
113 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW, &reassignbufsortbad, 0, "");
114 static int reassignbufmethod = 1;
115 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW, &reassignbufmethod, 0, "");
116 static int nameileafonly = 0;
117 SYSCTL_INT(_vfs, OID_AUTO, nameileafonly, CTLFLAG_RW, &nameileafonly, 0, "");
118 
119 #ifdef ENABLE_VFS_IOOPT
120 int vfs_ioopt = 0;
121 SYSCTL_INT(_vfs, OID_AUTO, ioopt, CTLFLAG_RW, &vfs_ioopt, 0, "");
122 #endif
123 
124 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist); /* mounted fs */
125 struct simplelock mountlist_slock;
126 struct simplelock mntvnode_slock;
127 int	nfs_mount_type = -1;
128 #ifndef NULL_SIMPLELOCKS
129 static struct simplelock mntid_slock;
130 static struct simplelock vnode_free_list_slock;
131 static struct simplelock spechash_slock;
132 #endif
133 struct nfs_public nfs_pub;	/* publicly exported FS */
134 static vm_zone_t vnode_zone;
135 
136 /*
137  * The workitem queue.
138  */
139 #define SYNCER_MAXDELAY		32
140 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
141 time_t syncdelay = 30;		/* max time to delay syncing data */
142 time_t filedelay = 30;		/* time to delay syncing files */
143 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
144 time_t dirdelay = 29;		/* time to delay syncing directories */
145 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
146 time_t metadelay = 28;		/* time to delay syncing metadata */
147 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
148 static int rushjob;			/* number of slots to run ASAP */
149 static int stat_rush_requests;	/* number of times I/O speeded up */
150 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
151 
152 static int syncer_delayno = 0;
153 static long syncer_mask;
154 LIST_HEAD(synclist, vnode);
155 static struct synclist *syncer_workitem_pending;
156 
157 int desiredvnodes;
158 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
159     &desiredvnodes, 0, "Maximum number of vnodes");
160 static int minvnodes;
161 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
162     &minvnodes, 0, "Minimum number of vnodes");
163 static int vnlru_nowhere = 0;
164 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW, &vnlru_nowhere, 0,
165     "Number of times the vnlru process ran without success");
166 
167 static void	vfs_free_addrlist __P((struct netexport *nep));
168 static int	vfs_free_netcred __P((struct radix_node *rn, void *w));
169 static int	vfs_hang_addrlist __P((struct mount *mp, struct netexport *nep,
170 				       struct export_args *argp));
171 
172 /*
173  * Initialize the vnode management data structures.
174  */
175 void
176 vntblinit()
177 {
178 
179 	desiredvnodes = maxproc + cnt.v_page_count / 4;
180 	minvnodes = desiredvnodes / 4;
181 	simple_lock_init(&mntvnode_slock);
182 	simple_lock_init(&mntid_slock);
183 	simple_lock_init(&spechash_slock);
184 	TAILQ_INIT(&vnode_free_list);
185 	simple_lock_init(&vnode_free_list_slock);
186 	vnode_zone = zinit("VNODE", sizeof (struct vnode), 0, 0, 5);
187 	/*
188 	 * Initialize the filesystem syncer.
189 	 */
190 	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
191 		&syncer_mask);
192 	syncer_maxdelay = syncer_mask + 1;
193 }
194 
195 /*
196  * Mark a mount point as busy. Used to synchronize access and to delay
197  * unmounting. Interlock is not released on failure.
198  */
199 int
200 vfs_busy(mp, flags, interlkp, p)
201 	struct mount *mp;
202 	int flags;
203 	struct simplelock *interlkp;
204 	struct proc *p;
205 {
206 	int lkflags;
207 
208 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
209 		if (flags & LK_NOWAIT)
210 			return (ENOENT);
211 		mp->mnt_kern_flag |= MNTK_MWAIT;
212 		if (interlkp) {
213 			simple_unlock(interlkp);
214 		}
215 		/*
216 		 * Since all busy locks are shared except the exclusive
217 		 * lock granted when unmounting, the only place that a
218 		 * wakeup needs to be done is at the release of the
219 		 * exclusive lock at the end of dounmount.
220 		 */
221 		tsleep((caddr_t)mp, PVFS, "vfs_busy", 0);
222 		if (interlkp) {
223 			simple_lock(interlkp);
224 		}
225 		return (ENOENT);
226 	}
227 	lkflags = LK_SHARED | LK_NOPAUSE;
228 	if (interlkp)
229 		lkflags |= LK_INTERLOCK;
230 	if (lockmgr(&mp->mnt_lock, lkflags, interlkp, p))
231 		panic("vfs_busy: unexpected lock failure");
232 	return (0);
233 }
234 
235 /*
236  * Free a busy filesystem.
237  */
238 void
239 vfs_unbusy(mp, p)
240 	struct mount *mp;
241 	struct proc *p;
242 {
243 
244 	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, p);
245 }
246 
247 /*
248  * Lookup a filesystem type, and if found allocate and initialize
249  * a mount structure for it.
250  *
251  * Devname is usually updated by mount(8) after booting.
252  */
253 int
254 vfs_rootmountalloc(fstypename, devname, mpp)
255 	char *fstypename;
256 	char *devname;
257 	struct mount **mpp;
258 {
259 	struct proc *p = curproc;	/* XXX */
260 	struct vfsconf *vfsp;
261 	struct mount *mp;
262 
263 	if (fstypename == NULL)
264 		return (ENODEV);
265 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
266 		if (!strcmp(vfsp->vfc_name, fstypename))
267 			break;
268 	if (vfsp == NULL)
269 		return (ENODEV);
270 	mp = malloc((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
271 	bzero((char *)mp, (u_long)sizeof(struct mount));
272 	lockinit(&mp->mnt_lock, PVFS, "vfslock", VLKTIMEOUT, LK_NOPAUSE);
273 	(void)vfs_busy(mp, LK_NOWAIT, 0, p);
274 	TAILQ_INIT(&mp->mnt_nvnodelist);
275 	TAILQ_INIT(&mp->mnt_reservedvnlist);
276 	mp->mnt_nvnodelistsize = 0;
277 	mp->mnt_vfc = vfsp;
278 	mp->mnt_op = vfsp->vfc_vfsops;
279 	mp->mnt_flag = MNT_RDONLY;
280 	mp->mnt_vnodecovered = NULLVP;
281 	vfsp->vfc_refcount++;
282 	mp->mnt_iosize_max = DFLTPHYS;
283 	mp->mnt_stat.f_type = vfsp->vfc_typenum;
284 	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
285 	strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
286 	mp->mnt_stat.f_mntonname[0] = '/';
287 	mp->mnt_stat.f_mntonname[1] = 0;
288 	(void) copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
289 	*mpp = mp;
290 	return (0);
291 }
292 
293 /*
294  * Find an appropriate filesystem to use for the root. If a filesystem
295  * has not been preselected, walk through the list of known filesystems
296  * trying those that have mountroot routines, and try them until one
297  * works or we have tried them all.
298  */
299 #ifdef notdef	/* XXX JH */
300 int
301 lite2_vfs_mountroot()
302 {
303 	struct vfsconf *vfsp;
304 	extern int (*lite2_mountroot) __P((void));
305 	int error;
306 
307 	if (lite2_mountroot != NULL)
308 		return ((*lite2_mountroot)());
309 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
310 		if (vfsp->vfc_mountroot == NULL)
311 			continue;
312 		if ((error = (*vfsp->vfc_mountroot)()) == 0)
313 			return (0);
314 		printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
315 	}
316 	return (ENODEV);
317 }
318 #endif
319 
320 /*
321  * Lookup a mount point by filesystem identifier.
322  */
323 struct mount *
324 vfs_getvfs(fsid)
325 	fsid_t *fsid;
326 {
327 	register struct mount *mp;
328 
329 	simple_lock(&mountlist_slock);
330 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
331 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
332 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
333 			simple_unlock(&mountlist_slock);
334 			return (mp);
335 	    }
336 	}
337 	simple_unlock(&mountlist_slock);
338 	return ((struct mount *) 0);
339 }
340 
341 /*
342  * Get a new unique fsid.  Try to make its val[0] unique, since this value
343  * will be used to create fake device numbers for stat().  Also try (but
344  * not so hard) make its val[0] unique mod 2^16, since some emulators only
345  * support 16-bit device numbers.  We end up with unique val[0]'s for the
346  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
347  *
348  * Keep in mind that several mounts may be running in parallel.  Starting
349  * the search one past where the previous search terminated is both a
350  * micro-optimization and a defense against returning the same fsid to
351  * different mounts.
352  */
353 void
354 vfs_getnewfsid(mp)
355 	struct mount *mp;
356 {
357 	static u_int16_t mntid_base;
358 	fsid_t tfsid;
359 	int mtype;
360 
361 	simple_lock(&mntid_slock);
362 	mtype = mp->mnt_vfc->vfc_typenum;
363 	tfsid.val[1] = mtype;
364 	mtype = (mtype & 0xFF) << 24;
365 	for (;;) {
366 		tfsid.val[0] = makeudev(255,
367 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
368 		mntid_base++;
369 		if (vfs_getvfs(&tfsid) == NULL)
370 			break;
371 	}
372 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
373 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
374 	simple_unlock(&mntid_slock);
375 }
376 
377 /*
378  * Knob to control the precision of file timestamps:
379  *
380  *   0 = seconds only; nanoseconds zeroed.
381  *   1 = seconds and nanoseconds, accurate within 1/HZ.
382  *   2 = seconds and nanoseconds, truncated to microseconds.
383  * >=3 = seconds and nanoseconds, maximum precision.
384  */
385 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
386 
387 static int timestamp_precision = TSP_SEC;
388 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
389     &timestamp_precision, 0, "");
390 
391 /*
392  * Get a current timestamp.
393  */
394 void
395 vfs_timestamp(tsp)
396 	struct timespec *tsp;
397 {
398 	struct timeval tv;
399 
400 	switch (timestamp_precision) {
401 	case TSP_SEC:
402 		tsp->tv_sec = time_second;
403 		tsp->tv_nsec = 0;
404 		break;
405 	case TSP_HZ:
406 		getnanotime(tsp);
407 		break;
408 	case TSP_USEC:
409 		microtime(&tv);
410 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
411 		break;
412 	case TSP_NSEC:
413 	default:
414 		nanotime(tsp);
415 		break;
416 	}
417 }
418 
419 /*
420  * Set vnode attributes to VNOVAL
421  */
422 void
423 vattr_null(vap)
424 	register struct vattr *vap;
425 {
426 
427 	vap->va_type = VNON;
428 	vap->va_size = VNOVAL;
429 	vap->va_bytes = VNOVAL;
430 	vap->va_mode = VNOVAL;
431 	vap->va_nlink = VNOVAL;
432 	vap->va_uid = VNOVAL;
433 	vap->va_gid = VNOVAL;
434 	vap->va_fsid = VNOVAL;
435 	vap->va_fileid = VNOVAL;
436 	vap->va_blocksize = VNOVAL;
437 	vap->va_rdev = VNOVAL;
438 	vap->va_atime.tv_sec = VNOVAL;
439 	vap->va_atime.tv_nsec = VNOVAL;
440 	vap->va_mtime.tv_sec = VNOVAL;
441 	vap->va_mtime.tv_nsec = VNOVAL;
442 	vap->va_ctime.tv_sec = VNOVAL;
443 	vap->va_ctime.tv_nsec = VNOVAL;
444 	vap->va_flags = VNOVAL;
445 	vap->va_gen = VNOVAL;
446 	vap->va_vaflags = 0;
447 }
448 
449 /*
450  * This routine is called when we have too many vnodes.  It attempts
451  * to free <count> vnodes and will potentially free vnodes that still
452  * have VM backing store (VM backing store is typically the cause
453  * of a vnode blowout so we want to do this).  Therefore, this operation
454  * is not considered cheap.
455  *
456  * A number of conditions may prevent a vnode from being reclaimed.
457  * the buffer cache may have references on the vnode, a directory
458  * vnode may still have references due to the namei cache representing
459  * underlying files, or the vnode may be in active use.   It is not
460  * desireable to reuse such vnodes.  These conditions may cause the
461  * number of vnodes to reach some minimum value regardless of what
462  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
463  */
464 static int
465 vlrureclaim(struct mount *mp)
466 {
467 	struct vnode *vp;
468 	int done;
469 	int trigger;
470 	int usevnodes;
471 	int count;
472 
473 	/*
474 	 * Calculate the trigger point, don't allow user
475 	 * screwups to blow us up.   This prevents us from
476 	 * recycling vnodes with lots of resident pages.  We
477 	 * aren't trying to free memory, we are trying to
478 	 * free vnodes.
479 	 */
480 	usevnodes = desiredvnodes;
481 	if (usevnodes <= 0)
482 		usevnodes = 1;
483 	trigger = cnt.v_page_count * 2 / usevnodes;
484 
485 	done = 0;
486 	simple_lock(&mntvnode_slock);
487 	count = mp->mnt_nvnodelistsize / 10 + 1;
488 	while (count && (vp = TAILQ_FIRST(&mp->mnt_nvnodelist)) != NULL) {
489 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
490 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
491 
492 		if (vp->v_type != VNON &&
493 		    vp->v_type != VBAD &&
494 		    VMIGHTFREE(vp) &&		/* critical path opt */
495 		    (vp->v_object == NULL || vp->v_object->resident_page_count < trigger) &&
496 		    simple_lock_try(&vp->v_interlock)
497 		) {
498 			simple_unlock(&mntvnode_slock);
499 			if (VMIGHTFREE(vp)) {
500 				vgonel(vp, curproc);
501 				done++;
502 			} else {
503 				simple_unlock(&vp->v_interlock);
504 			}
505 			simple_lock(&mntvnode_slock);
506 		}
507 		--count;
508 	}
509 	simple_unlock(&mntvnode_slock);
510 	return done;
511 }
512 
513 /*
514  * Attempt to recycle vnodes in a context that is always safe to block.
515  * Calling vlrurecycle() from the bowels of file system code has some
516  * interesting deadlock problems.
517  */
518 static struct proc *vnlruproc;
519 static int vnlruproc_sig;
520 
521 static void
522 vnlru_proc(void)
523 {
524 	struct mount *mp, *nmp;
525 	int s;
526 	int done;
527 	struct proc *p = vnlruproc;
528 
529 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, p,
530 	    SHUTDOWN_PRI_FIRST);
531 
532 	s = splbio();
533 	for (;;) {
534 		kproc_suspend_loop(p);
535 		if (numvnodes - freevnodes <= desiredvnodes * 9 / 10) {
536 			vnlruproc_sig = 0;
537 			wakeup(&vnlruproc_sig);
538 			tsleep(vnlruproc, PVFS, "vlruwt", hz);
539 			continue;
540 		}
541 		done = 0;
542 		simple_lock(&mountlist_slock);
543 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
544 			if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock, p)) {
545 				nmp = TAILQ_NEXT(mp, mnt_list);
546 				continue;
547 			}
548 			done += vlrureclaim(mp);
549 			simple_lock(&mountlist_slock);
550 			nmp = TAILQ_NEXT(mp, mnt_list);
551 			vfs_unbusy(mp, p);
552 		}
553 		simple_unlock(&mountlist_slock);
554 		if (done == 0) {
555 			vnlru_nowhere++;
556 			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
557 		}
558 	}
559 	splx(s);
560 }
561 
562 static struct kproc_desc vnlru_kp = {
563 	"vnlru",
564 	vnlru_proc,
565 	&vnlruproc
566 };
567 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
568 
569 /*
570  * Routines having to do with the management of the vnode table.
571  */
572 extern vop_t **dead_vnodeop_p;
573 
574 /*
575  * Return the next vnode from the free list.
576  */
577 int
578 getnewvnode(tag, mp, vops, vpp)
579 	enum vtagtype tag;
580 	struct mount *mp;
581 	vop_t **vops;
582 	struct vnode **vpp;
583 {
584 	int s;
585 	struct proc *p = curproc;	/* XXX */
586 	struct vnode *vp = NULL;
587 	vm_object_t object;
588 
589 	s = splbio();
590 
591 	/*
592 	 * Try to reuse vnodes if we hit the max.  This situation only
593 	 * occurs in certain large-memory (2G+) situations.  We cannot
594 	 * attempt to directly reclaim vnodes due to nasty recursion
595 	 * problems.
596 	 */
597 	while (numvnodes - freevnodes > desiredvnodes) {
598 		if (vnlruproc_sig == 0) {
599 			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
600 			wakeup(vnlruproc);
601 		}
602 		tsleep(&vnlruproc_sig, PVFS, "vlruwk", hz);
603 	}
604 
605 
606 	/*
607 	 * Attempt to reuse a vnode already on the free list, allocating
608 	 * a new vnode if we can't find one or if we have not reached a
609 	 * good minimum for good LRU performance.
610 	 */
611 	simple_lock(&vnode_free_list_slock);
612 	if (freevnodes >= wantfreevnodes && numvnodes >= minvnodes) {
613 		int count;
614 
615 		for (count = 0; count < freevnodes; count++) {
616 			vp = TAILQ_FIRST(&vnode_free_list);
617 			if (vp == NULL || vp->v_usecount)
618 				panic("getnewvnode: free vnode isn't");
619 
620 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
621 			if ((VOP_GETVOBJECT(vp, &object) == 0 &&
622 			    (object->resident_page_count || object->ref_count)) ||
623 			    !simple_lock_try(&vp->v_interlock)) {
624 				TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
625 				vp = NULL;
626 				continue;
627 			}
628 			if (LIST_FIRST(&vp->v_cache_src)) {
629 				/*
630 				 * note: nameileafonly sysctl is temporary,
631 				 * for debugging only, and will eventually be
632 				 * removed.
633 				 */
634 				if (nameileafonly > 0) {
635 					/*
636 					 * Do not reuse namei-cached directory
637 					 * vnodes that have cached
638 					 * subdirectories.
639 					 */
640 					if (cache_leaf_test(vp) < 0) {
641 						simple_unlock(&vp->v_interlock);
642 						TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
643 						vp = NULL;
644 						continue;
645 					}
646 				} else if (nameileafonly < 0 ||
647 					    vmiodirenable == 0) {
648 					/*
649 					 * Do not reuse namei-cached directory
650 					 * vnodes if nameileafonly is -1 or
651 					 * if VMIO backing for directories is
652 					 * turned off (otherwise we reuse them
653 					 * too quickly).
654 					 */
655 					simple_unlock(&vp->v_interlock);
656 					TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
657 					vp = NULL;
658 					continue;
659 				}
660 			}
661 			break;
662 		}
663 	}
664 
665 	if (vp) {
666 		vp->v_flag |= VDOOMED;
667 		vp->v_flag &= ~VFREE;
668 		freevnodes--;
669 		simple_unlock(&vnode_free_list_slock);
670 		cache_purge(vp);
671 		vp->v_lease = NULL;
672 		if (vp->v_type != VBAD) {
673 			vgonel(vp, p);
674 		} else {
675 			simple_unlock(&vp->v_interlock);
676 		}
677 
678 #ifdef INVARIANTS
679 		{
680 			int s;
681 
682 			if (vp->v_data)
683 				panic("cleaned vnode isn't");
684 			s = splbio();
685 			if (vp->v_numoutput)
686 				panic("Clean vnode has pending I/O's");
687 			splx(s);
688 		}
689 #endif
690 		vp->v_flag = 0;
691 		vp->v_lastw = 0;
692 		vp->v_lasta = 0;
693 		vp->v_cstart = 0;
694 		vp->v_clen = 0;
695 		vp->v_socket = 0;
696 		vp->v_writecount = 0;	/* XXX */
697 	} else {
698 		simple_unlock(&vnode_free_list_slock);
699 		vp = (struct vnode *) zalloc(vnode_zone);
700 		bzero((char *) vp, sizeof *vp);
701 		simple_lock_init(&vp->v_interlock);
702 		vp->v_dd = vp;
703 		cache_purge(vp);
704 		LIST_INIT(&vp->v_cache_src);
705 		TAILQ_INIT(&vp->v_cache_dst);
706 		numvnodes++;
707 	}
708 
709 	TAILQ_INIT(&vp->v_cleanblkhd);
710 	TAILQ_INIT(&vp->v_dirtyblkhd);
711 	vp->v_type = VNON;
712 	vp->v_tag = tag;
713 	vp->v_op = vops;
714 	insmntque(vp, mp);
715 	*vpp = vp;
716 	vp->v_usecount = 1;
717 	vp->v_data = 0;
718 	splx(s);
719 
720 	vfs_object_create(vp, p, p->p_ucred);
721 	return (0);
722 }
723 
724 /*
725  * Move a vnode from one mount queue to another.
726  */
727 static void
728 insmntque(vp, mp)
729 	register struct vnode *vp;
730 	register struct mount *mp;
731 {
732 
733 	simple_lock(&mntvnode_slock);
734 	/*
735 	 * Delete from old mount point vnode list, if on one.
736 	 */
737 	if (vp->v_mount != NULL) {
738 		KASSERT(vp->v_mount->mnt_nvnodelistsize > 0,
739 			("bad mount point vnode list size"));
740 		TAILQ_REMOVE(&vp->v_mount->mnt_nvnodelist, vp, v_nmntvnodes);
741 		vp->v_mount->mnt_nvnodelistsize--;
742 	}
743 	/*
744 	 * Insert into list of vnodes for the new mount point, if available.
745 	 */
746 	if ((vp->v_mount = mp) == NULL) {
747 		simple_unlock(&mntvnode_slock);
748 		return;
749 	}
750 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
751 	mp->mnt_nvnodelistsize++;
752 	simple_unlock(&mntvnode_slock);
753 }
754 
755 /*
756  * Update outstanding I/O count and do wakeup if requested.
757  */
758 void
759 vwakeup(bp)
760 	register struct buf *bp;
761 {
762 	register struct vnode *vp;
763 
764 	bp->b_flags &= ~B_WRITEINPROG;
765 	if ((vp = bp->b_vp)) {
766 		vp->v_numoutput--;
767 		if (vp->v_numoutput < 0)
768 			panic("vwakeup: neg numoutput");
769 		if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
770 			vp->v_flag &= ~VBWAIT;
771 			wakeup((caddr_t) &vp->v_numoutput);
772 		}
773 	}
774 }
775 
776 /*
777  * Flush out and invalidate all buffers associated with a vnode.
778  * Called with the underlying object locked.
779  */
780 int
781 vinvalbuf(vp, flags, cred, p, slpflag, slptimeo)
782 	register struct vnode *vp;
783 	int flags;
784 	struct ucred *cred;
785 	struct proc *p;
786 	int slpflag, slptimeo;
787 {
788 	register struct buf *bp;
789 	struct buf *nbp, *blist;
790 	int s, error;
791 	vm_object_t object;
792 
793 	if (flags & V_SAVE) {
794 		s = splbio();
795 		while (vp->v_numoutput) {
796 			vp->v_flag |= VBWAIT;
797 			error = tsleep((caddr_t)&vp->v_numoutput,
798 			    slpflag | (PRIBIO + 1), "vinvlbuf", slptimeo);
799 			if (error) {
800 				splx(s);
801 				return (error);
802 			}
803 		}
804 		if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
805 			splx(s);
806 			if ((error = VOP_FSYNC(vp, cred, MNT_WAIT, p)) != 0)
807 				return (error);
808 			s = splbio();
809 			if (vp->v_numoutput > 0 ||
810 			    !TAILQ_EMPTY(&vp->v_dirtyblkhd))
811 				panic("vinvalbuf: dirty bufs");
812 		}
813 		splx(s);
814   	}
815 	s = splbio();
816 	for (;;) {
817 		blist = TAILQ_FIRST(&vp->v_cleanblkhd);
818 		if (!blist)
819 			blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
820 		if (!blist)
821 			break;
822 
823 		for (bp = blist; bp; bp = nbp) {
824 			nbp = TAILQ_NEXT(bp, b_vnbufs);
825 			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
826 				error = BUF_TIMELOCK(bp,
827 				    LK_EXCLUSIVE | LK_SLEEPFAIL,
828 				    "vinvalbuf", slpflag, slptimeo);
829 				if (error == ENOLCK)
830 					break;
831 				splx(s);
832 				return (error);
833 			}
834 			/*
835 			 * XXX Since there are no node locks for NFS, I
836 			 * believe there is a slight chance that a delayed
837 			 * write will occur while sleeping just above, so
838 			 * check for it.  Note that vfs_bio_awrite expects
839 			 * buffers to reside on a queue, while VOP_BWRITE and
840 			 * brelse do not.
841 			 */
842 			if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
843 				(flags & V_SAVE)) {
844 
845 				if (bp->b_vp == vp) {
846 					if (bp->b_flags & B_CLUSTEROK) {
847 						BUF_UNLOCK(bp);
848 						vfs_bio_awrite(bp);
849 					} else {
850 						bremfree(bp);
851 						bp->b_flags |= B_ASYNC;
852 						VOP_BWRITE(bp->b_vp, bp);
853 					}
854 				} else {
855 					bremfree(bp);
856 					(void) VOP_BWRITE(bp->b_vp, bp);
857 				}
858 				break;
859 			}
860 			bremfree(bp);
861 			bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
862 			bp->b_flags &= ~B_ASYNC;
863 			brelse(bp);
864 		}
865 	}
866 
867 	/*
868 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
869 	 * have write I/O in-progress but if there is a VM object then the
870 	 * VM object can also have read-I/O in-progress.
871 	 */
872 	do {
873 		while (vp->v_numoutput > 0) {
874 			vp->v_flag |= VBWAIT;
875 			tsleep(&vp->v_numoutput, PVM, "vnvlbv", 0);
876 		}
877 		if (VOP_GETVOBJECT(vp, &object) == 0) {
878 			while (object->paging_in_progress)
879 				vm_object_pip_sleep(object, "vnvlbx");
880 		}
881 	} while (vp->v_numoutput > 0);
882 
883 	splx(s);
884 
885 	/*
886 	 * Destroy the copy in the VM cache, too.
887 	 */
888 	simple_lock(&vp->v_interlock);
889 	if (VOP_GETVOBJECT(vp, &object) == 0) {
890 		vm_object_page_remove(object, 0, 0,
891 			(flags & V_SAVE) ? TRUE : FALSE);
892 	}
893 	simple_unlock(&vp->v_interlock);
894 
895 	if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
896 		panic("vinvalbuf: flush failed");
897 	return (0);
898 }
899 
900 /*
901  * Truncate a file's buffer and pages to a specified length.  This
902  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
903  * sync activity.
904  */
905 int
906 vtruncbuf(vp, cred, p, length, blksize)
907 	register struct vnode *vp;
908 	struct ucred *cred;
909 	struct proc *p;
910 	off_t length;
911 	int blksize;
912 {
913 	register struct buf *bp;
914 	struct buf *nbp;
915 	int s, anyfreed;
916 	int trunclbn;
917 
918 	/*
919 	 * Round up to the *next* lbn.
920 	 */
921 	trunclbn = (length + blksize - 1) / blksize;
922 
923 	s = splbio();
924 restart:
925 	anyfreed = 1;
926 	for (;anyfreed;) {
927 		anyfreed = 0;
928 		for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
929 			nbp = TAILQ_NEXT(bp, b_vnbufs);
930 			if (bp->b_lblkno >= trunclbn) {
931 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
932 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
933 					goto restart;
934 				} else {
935 					bremfree(bp);
936 					bp->b_flags |= (B_INVAL | B_RELBUF);
937 					bp->b_flags &= ~B_ASYNC;
938 					brelse(bp);
939 					anyfreed = 1;
940 				}
941 				if (nbp &&
942 				    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
943 				    (nbp->b_vp != vp) ||
944 				    (nbp->b_flags & B_DELWRI))) {
945 					goto restart;
946 				}
947 			}
948 		}
949 
950 		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
951 			nbp = TAILQ_NEXT(bp, b_vnbufs);
952 			if (bp->b_lblkno >= trunclbn) {
953 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
954 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
955 					goto restart;
956 				} else {
957 					bremfree(bp);
958 					bp->b_flags |= (B_INVAL | B_RELBUF);
959 					bp->b_flags &= ~B_ASYNC;
960 					brelse(bp);
961 					anyfreed = 1;
962 				}
963 				if (nbp &&
964 				    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
965 				    (nbp->b_vp != vp) ||
966 				    (nbp->b_flags & B_DELWRI) == 0)) {
967 					goto restart;
968 				}
969 			}
970 		}
971 	}
972 
973 	if (length > 0) {
974 restartsync:
975 		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
976 			nbp = TAILQ_NEXT(bp, b_vnbufs);
977 			if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
978 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
979 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
980 					goto restart;
981 				} else {
982 					bremfree(bp);
983 					if (bp->b_vp == vp) {
984 						bp->b_flags |= B_ASYNC;
985 					} else {
986 						bp->b_flags &= ~B_ASYNC;
987 					}
988 					VOP_BWRITE(bp->b_vp, bp);
989 				}
990 				goto restartsync;
991 			}
992 
993 		}
994 	}
995 
996 	while (vp->v_numoutput > 0) {
997 		vp->v_flag |= VBWAIT;
998 		tsleep(&vp->v_numoutput, PVM, "vbtrunc", 0);
999 	}
1000 
1001 	splx(s);
1002 
1003 	vnode_pager_setsize(vp, length);
1004 
1005 	return (0);
1006 }
1007 
1008 /*
1009  * Associate a buffer with a vnode.
1010  */
1011 void
1012 bgetvp(vp, bp)
1013 	register struct vnode *vp;
1014 	register struct buf *bp;
1015 {
1016 	int s;
1017 
1018 	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
1019 
1020 	vhold(vp);
1021 	bp->b_vp = vp;
1022 	bp->b_dev = vn_todev(vp);
1023 	/*
1024 	 * Insert onto list for new vnode.
1025 	 */
1026 	s = splbio();
1027 	bp->b_xflags |= BX_VNCLEAN;
1028 	bp->b_xflags &= ~BX_VNDIRTY;
1029 	TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
1030 	splx(s);
1031 }
1032 
1033 /*
1034  * Disassociate a buffer from a vnode.
1035  */
1036 void
1037 brelvp(bp)
1038 	register struct buf *bp;
1039 {
1040 	struct vnode *vp;
1041 	struct buflists *listheadp;
1042 	int s;
1043 
1044 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1045 
1046 	/*
1047 	 * Delete from old vnode list, if on one.
1048 	 */
1049 	vp = bp->b_vp;
1050 	s = splbio();
1051 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1052 		if (bp->b_xflags & BX_VNDIRTY)
1053 			listheadp = &vp->v_dirtyblkhd;
1054 		else
1055 			listheadp = &vp->v_cleanblkhd;
1056 		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1057 		bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1058 	}
1059 	if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
1060 		vp->v_flag &= ~VONWORKLST;
1061 		LIST_REMOVE(vp, v_synclist);
1062 	}
1063 	splx(s);
1064 	bp->b_vp = (struct vnode *) 0;
1065 	vdrop(vp);
1066 }
1067 
1068 /*
1069  * The workitem queue.
1070  *
1071  * It is useful to delay writes of file data and filesystem metadata
1072  * for tens of seconds so that quickly created and deleted files need
1073  * not waste disk bandwidth being created and removed. To realize this,
1074  * we append vnodes to a "workitem" queue. When running with a soft
1075  * updates implementation, most pending metadata dependencies should
1076  * not wait for more than a few seconds. Thus, mounted on block devices
1077  * are delayed only about a half the time that file data is delayed.
1078  * Similarly, directory updates are more critical, so are only delayed
1079  * about a third the time that file data is delayed. Thus, there are
1080  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
1081  * one each second (driven off the filesystem syncer process). The
1082  * syncer_delayno variable indicates the next queue that is to be processed.
1083  * Items that need to be processed soon are placed in this queue:
1084  *
1085  *	syncer_workitem_pending[syncer_delayno]
1086  *
1087  * A delay of fifteen seconds is done by placing the request fifteen
1088  * entries later in the queue:
1089  *
1090  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
1091  *
1092  */
1093 
1094 /*
1095  * Add an item to the syncer work queue.
1096  */
1097 static void
1098 vn_syncer_add_to_worklist(struct vnode *vp, int delay)
1099 {
1100 	int s, slot;
1101 
1102 	s = splbio();
1103 
1104 	if (vp->v_flag & VONWORKLST) {
1105 		LIST_REMOVE(vp, v_synclist);
1106 	}
1107 
1108 	if (delay > syncer_maxdelay - 2)
1109 		delay = syncer_maxdelay - 2;
1110 	slot = (syncer_delayno + delay) & syncer_mask;
1111 
1112 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], vp, v_synclist);
1113 	vp->v_flag |= VONWORKLST;
1114 	splx(s);
1115 }
1116 
1117 struct  proc *updateproc;
1118 static void sched_sync __P((void));
1119 static struct kproc_desc up_kp = {
1120 	"syncer",
1121 	sched_sync,
1122 	&updateproc
1123 };
1124 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1125 
1126 /*
1127  * System filesystem synchronizer daemon.
1128  */
1129 void
1130 sched_sync(void)
1131 {
1132 	struct synclist *slp;
1133 	struct vnode *vp;
1134 	long starttime;
1135 	int s;
1136 	struct proc *p = updateproc;
1137 
1138 	EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, p,
1139 	    SHUTDOWN_PRI_LAST);
1140 
1141 	for (;;) {
1142 		kproc_suspend_loop(p);
1143 
1144 		starttime = time_second;
1145 
1146 		/*
1147 		 * Push files whose dirty time has expired.  Be careful
1148 		 * of interrupt race on slp queue.
1149 		 */
1150 		s = splbio();
1151 		slp = &syncer_workitem_pending[syncer_delayno];
1152 		syncer_delayno += 1;
1153 		if (syncer_delayno == syncer_maxdelay)
1154 			syncer_delayno = 0;
1155 		splx(s);
1156 
1157 		while ((vp = LIST_FIRST(slp)) != NULL) {
1158 			if (VOP_ISLOCKED(vp, NULL) == 0) {
1159 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
1160 				(void) VOP_FSYNC(vp, p->p_ucred, MNT_LAZY, p);
1161 				VOP_UNLOCK(vp, 0, p);
1162 			}
1163 			s = splbio();
1164 			if (LIST_FIRST(slp) == vp) {
1165 				/*
1166 				 * Note: v_tag VT_VFS vps can remain on the
1167 				 * worklist too with no dirty blocks, but
1168 				 * since sync_fsync() moves it to a different
1169 				 * slot we are safe.
1170 				 */
1171 				if (TAILQ_EMPTY(&vp->v_dirtyblkhd) &&
1172 				    !vn_isdisk(vp, NULL))
1173 					panic("sched_sync: fsync failed vp %p tag %d", vp, vp->v_tag);
1174 				/*
1175 				 * Put us back on the worklist.  The worklist
1176 				 * routine will remove us from our current
1177 				 * position and then add us back in at a later
1178 				 * position.
1179 				 */
1180 				vn_syncer_add_to_worklist(vp, syncdelay);
1181 			}
1182 			splx(s);
1183 		}
1184 
1185 		/*
1186 		 * Do soft update processing.
1187 		 */
1188 		if (bioops.io_sync)
1189 			(*bioops.io_sync)(NULL);
1190 
1191 		/*
1192 		 * The variable rushjob allows the kernel to speed up the
1193 		 * processing of the filesystem syncer process. A rushjob
1194 		 * value of N tells the filesystem syncer to process the next
1195 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1196 		 * is used by the soft update code to speed up the filesystem
1197 		 * syncer process when the incore state is getting so far
1198 		 * ahead of the disk that the kernel memory pool is being
1199 		 * threatened with exhaustion.
1200 		 */
1201 		if (rushjob > 0) {
1202 			rushjob -= 1;
1203 			continue;
1204 		}
1205 		/*
1206 		 * If it has taken us less than a second to process the
1207 		 * current work, then wait. Otherwise start right over
1208 		 * again. We can still lose time if any single round
1209 		 * takes more than two seconds, but it does not really
1210 		 * matter as we are just trying to generally pace the
1211 		 * filesystem activity.
1212 		 */
1213 		if (time_second == starttime)
1214 			tsleep(&lbolt, PPAUSE, "syncer", 0);
1215 	}
1216 }
1217 
1218 /*
1219  * Request the syncer daemon to speed up its work.
1220  * We never push it to speed up more than half of its
1221  * normal turn time, otherwise it could take over the cpu.
1222  */
1223 int
1224 speedup_syncer()
1225 {
1226 	int s;
1227 
1228 	s = splhigh();
1229 	if (updateproc->p_wchan == &lbolt)
1230 		setrunnable(updateproc);
1231 	splx(s);
1232 	if (rushjob < syncdelay / 2) {
1233 		rushjob += 1;
1234 		stat_rush_requests += 1;
1235 		return (1);
1236 	}
1237 	return(0);
1238 }
1239 
1240 /*
1241  * Associate a p-buffer with a vnode.
1242  *
1243  * Also sets B_PAGING flag to indicate that vnode is not fully associated
1244  * with the buffer.  i.e. the bp has not been linked into the vnode or
1245  * ref-counted.
1246  */
1247 void
1248 pbgetvp(vp, bp)
1249 	register struct vnode *vp;
1250 	register struct buf *bp;
1251 {
1252 
1253 	KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
1254 
1255 	bp->b_vp = vp;
1256 	bp->b_flags |= B_PAGING;
1257 	bp->b_dev = vn_todev(vp);
1258 }
1259 
1260 /*
1261  * Disassociate a p-buffer from a vnode.
1262  */
1263 void
1264 pbrelvp(bp)
1265 	register struct buf *bp;
1266 {
1267 
1268 	KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
1269 
1270 	/* XXX REMOVE ME */
1271 	if (TAILQ_NEXT(bp, b_vnbufs) != NULL) {
1272 		panic(
1273 		    "relpbuf(): b_vp was probably reassignbuf()d %p %x",
1274 		    bp,
1275 		    (int)bp->b_flags
1276 		);
1277 	}
1278 	bp->b_vp = (struct vnode *) 0;
1279 	bp->b_flags &= ~B_PAGING;
1280 }
1281 
1282 void
1283 pbreassignbuf(bp, newvp)
1284 	struct buf *bp;
1285 	struct vnode *newvp;
1286 {
1287 	if ((bp->b_flags & B_PAGING) == 0) {
1288 		panic(
1289 		    "pbreassignbuf() on non phys bp %p",
1290 		    bp
1291 		);
1292 	}
1293 	bp->b_vp = newvp;
1294 }
1295 
1296 /*
1297  * Reassign a buffer from one vnode to another.
1298  * Used to assign file specific control information
1299  * (indirect blocks) to the vnode to which they belong.
1300  */
1301 void
1302 reassignbuf(bp, newvp)
1303 	register struct buf *bp;
1304 	register struct vnode *newvp;
1305 {
1306 	struct buflists *listheadp;
1307 	int delay;
1308 	int s;
1309 
1310 	if (newvp == NULL) {
1311 		printf("reassignbuf: NULL");
1312 		return;
1313 	}
1314 	++reassignbufcalls;
1315 
1316 	/*
1317 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1318 	 * is not fully linked in.
1319 	 */
1320 	if (bp->b_flags & B_PAGING)
1321 		panic("cannot reassign paging buffer");
1322 
1323 	s = splbio();
1324 	/*
1325 	 * Delete from old vnode list, if on one.
1326 	 */
1327 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1328 		if (bp->b_xflags & BX_VNDIRTY)
1329 			listheadp = &bp->b_vp->v_dirtyblkhd;
1330 		else
1331 			listheadp = &bp->b_vp->v_cleanblkhd;
1332 		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1333 		bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1334 		if (bp->b_vp != newvp) {
1335 			vdrop(bp->b_vp);
1336 			bp->b_vp = NULL;	/* for clarification */
1337 		}
1338 	}
1339 	/*
1340 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1341 	 * of clean buffers.
1342 	 */
1343 	if (bp->b_flags & B_DELWRI) {
1344 		struct buf *tbp;
1345 
1346 		listheadp = &newvp->v_dirtyblkhd;
1347 		if ((newvp->v_flag & VONWORKLST) == 0) {
1348 			switch (newvp->v_type) {
1349 			case VDIR:
1350 				delay = dirdelay;
1351 				break;
1352 			case VCHR:
1353 			case VBLK:
1354 				if (newvp->v_specmountpoint != NULL) {
1355 					delay = metadelay;
1356 					break;
1357 				}
1358 				/* fall through */
1359 			default:
1360 				delay = filedelay;
1361 			}
1362 			vn_syncer_add_to_worklist(newvp, delay);
1363 		}
1364 		bp->b_xflags |= BX_VNDIRTY;
1365 		tbp = TAILQ_FIRST(listheadp);
1366 		if (tbp == NULL ||
1367 		    bp->b_lblkno == 0 ||
1368 		    (bp->b_lblkno > 0 && tbp->b_lblkno < 0) ||
1369 		    (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
1370 			TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1371 			++reassignbufsortgood;
1372 		} else if (bp->b_lblkno < 0) {
1373 			TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
1374 			++reassignbufsortgood;
1375 		} else if (reassignbufmethod == 1) {
1376 			/*
1377 			 * New sorting algorithm, only handle sequential case,
1378 			 * otherwise append to end (but before metadata)
1379 			 */
1380 			if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
1381 			    (tbp->b_xflags & BX_VNDIRTY)) {
1382 				/*
1383 				 * Found the best place to insert the buffer
1384 				 */
1385 				TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1386 				++reassignbufsortgood;
1387 			} else {
1388 				/*
1389 				 * Missed, append to end, but before meta-data.
1390 				 * We know that the head buffer in the list is
1391 				 * not meta-data due to prior conditionals.
1392 				 *
1393 				 * Indirect effects:  NFS second stage write
1394 				 * tends to wind up here, giving maximum
1395 				 * distance between the unstable write and the
1396 				 * commit rpc.
1397 				 */
1398 				tbp = TAILQ_LAST(listheadp, buflists);
1399 				while (tbp && tbp->b_lblkno < 0)
1400 					tbp = TAILQ_PREV(tbp, buflists, b_vnbufs);
1401 				TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1402 				++reassignbufsortbad;
1403 			}
1404 		} else {
1405 			/*
1406 			 * Old sorting algorithm, scan queue and insert
1407 			 */
1408 			struct buf *ttbp;
1409 			while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
1410 			    (ttbp->b_lblkno < bp->b_lblkno)) {
1411 				++reassignbufloops;
1412 				tbp = ttbp;
1413 			}
1414 			TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1415 		}
1416 	} else {
1417 		bp->b_xflags |= BX_VNCLEAN;
1418 		TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
1419 		if ((newvp->v_flag & VONWORKLST) &&
1420 		    TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
1421 			newvp->v_flag &= ~VONWORKLST;
1422 			LIST_REMOVE(newvp, v_synclist);
1423 		}
1424 	}
1425 	if (bp->b_vp != newvp) {
1426 		bp->b_vp = newvp;
1427 		vhold(bp->b_vp);
1428 	}
1429 	splx(s);
1430 }
1431 
1432 /*
1433  * Create a vnode for a block device.
1434  * Used for mounting the root file system.
1435  */
1436 int
1437 bdevvp(dev, vpp)
1438 	dev_t dev;
1439 	struct vnode **vpp;
1440 {
1441 	register struct vnode *vp;
1442 	struct vnode *nvp;
1443 	int error;
1444 
1445 	if (dev == NODEV) {
1446 		*vpp = NULLVP;
1447 		return (ENXIO);
1448 	}
1449 	error = getnewvnode(VT_NON, (struct mount *)0, spec_vnodeop_p, &nvp);
1450 	if (error) {
1451 		*vpp = NULLVP;
1452 		return (error);
1453 	}
1454 	vp = nvp;
1455 	vp->v_type = VBLK;
1456 	addalias(vp, dev);
1457 	*vpp = vp;
1458 	return (0);
1459 }
1460 
1461 /*
1462  * Add vnode to the alias list hung off the dev_t.
1463  *
1464  * The reason for this gunk is that multiple vnodes can reference
1465  * the same physical device, so checking vp->v_usecount to see
1466  * how many users there are is inadequate; the v_usecount for
1467  * the vnodes need to be accumulated.  vcount() does that.
1468  */
1469 void
1470 addaliasu(nvp, nvp_rdev)
1471 	struct vnode *nvp;
1472 	udev_t nvp_rdev;
1473 {
1474 
1475 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1476 		panic("addaliasu on non-special vnode");
1477 	addalias(nvp, udev2dev(nvp_rdev, nvp->v_type == VBLK ? 1 : 0));
1478 }
1479 
1480 void
1481 addalias(nvp, dev)
1482 	struct vnode *nvp;
1483 	dev_t dev;
1484 {
1485 
1486 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1487 		panic("addalias on non-special vnode");
1488 
1489 	nvp->v_rdev = dev;
1490 	simple_lock(&spechash_slock);
1491 	SLIST_INSERT_HEAD(&dev->si_hlist, nvp, v_specnext);
1492 	simple_unlock(&spechash_slock);
1493 }
1494 
1495 /*
1496  * Grab a particular vnode from the free list, increment its
1497  * reference count and lock it. The vnode lock bit is set if the
1498  * vnode is being eliminated in vgone. The process is awakened
1499  * when the transition is completed, and an error returned to
1500  * indicate that the vnode is no longer usable (possibly having
1501  * been changed to a new file system type).
1502  */
1503 int
1504 vget(vp, flags, p)
1505 	register struct vnode *vp;
1506 	int flags;
1507 	struct proc *p;
1508 {
1509 	int error;
1510 
1511 	/*
1512 	 * If the vnode is in the process of being cleaned out for
1513 	 * another use, we wait for the cleaning to finish and then
1514 	 * return failure. Cleaning is determined by checking that
1515 	 * the VXLOCK flag is set.
1516 	 */
1517 	if ((flags & LK_INTERLOCK) == 0) {
1518 		simple_lock(&vp->v_interlock);
1519 	}
1520 	if (vp->v_flag & VXLOCK) {
1521 		if (vp->v_vxproc == curproc) {
1522 #if 0
1523 			/* this can now occur in normal operation */
1524 			log(LOG_INFO, "VXLOCK interlock avoided\n");
1525 #endif
1526 		} else {
1527 			vp->v_flag |= VXWANT;
1528 			simple_unlock(&vp->v_interlock);
1529 			tsleep((caddr_t)vp, PINOD, "vget", 0);
1530 			return (ENOENT);
1531 		}
1532 	}
1533 
1534 	vp->v_usecount++;
1535 
1536 	if (VSHOULDBUSY(vp))
1537 		vbusy(vp);
1538 	if (flags & LK_TYPE_MASK) {
1539 		if ((error = vn_lock(vp, flags | LK_INTERLOCK, p)) != 0) {
1540 			/*
1541 			 * must expand vrele here because we do not want
1542 			 * to call VOP_INACTIVE if the reference count
1543 			 * drops back to zero since it was never really
1544 			 * active. We must remove it from the free list
1545 			 * before sleeping so that multiple processes do
1546 			 * not try to recycle it.
1547 			 */
1548 			simple_lock(&vp->v_interlock);
1549 			vp->v_usecount--;
1550 			if (VSHOULDFREE(vp))
1551 				vfree(vp);
1552 			else
1553 				vlruvp(vp);
1554 			simple_unlock(&vp->v_interlock);
1555 		}
1556 		return (error);
1557 	}
1558 	simple_unlock(&vp->v_interlock);
1559 	return (0);
1560 }
1561 
1562 void
1563 vref(struct vnode *vp)
1564 {
1565 	simple_lock(&vp->v_interlock);
1566 	vp->v_usecount++;
1567 	simple_unlock(&vp->v_interlock);
1568 }
1569 
1570 /*
1571  * Vnode put/release.
1572  * If count drops to zero, call inactive routine and return to freelist.
1573  */
1574 void
1575 vrele(vp)
1576 	struct vnode *vp;
1577 {
1578 	struct proc *p = curproc;	/* XXX */
1579 
1580 	KASSERT(vp != NULL, ("vrele: null vp"));
1581 
1582 	simple_lock(&vp->v_interlock);
1583 
1584 	if (vp->v_usecount > 1) {
1585 
1586 		vp->v_usecount--;
1587 		simple_unlock(&vp->v_interlock);
1588 
1589 		return;
1590 	}
1591 
1592 	if (vp->v_usecount == 1) {
1593 		vp->v_usecount--;
1594 		/*
1595 		 * We must call VOP_INACTIVE with the node locked.
1596 		 * If we are doing a vpu, the node is already locked,
1597 		 * but, in the case of vrele, we must explicitly lock
1598 		 * the vnode before calling VOP_INACTIVE
1599 		 */
1600 
1601 		if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, p) == 0)
1602 			VOP_INACTIVE(vp, p);
1603 		if (VSHOULDFREE(vp))
1604 			vfree(vp);
1605 		else
1606 			vlruvp(vp);
1607 	} else {
1608 #ifdef DIAGNOSTIC
1609 		vprint("vrele: negative ref count", vp);
1610 		simple_unlock(&vp->v_interlock);
1611 #endif
1612 		panic("vrele: negative ref cnt");
1613 	}
1614 }
1615 
1616 void
1617 vput(vp)
1618 	struct vnode *vp;
1619 {
1620 	struct proc *p = curproc;	/* XXX */
1621 
1622 	KASSERT(vp != NULL, ("vput: null vp"));
1623 
1624 	simple_lock(&vp->v_interlock);
1625 
1626 	if (vp->v_usecount > 1) {
1627 		vp->v_usecount--;
1628 		VOP_UNLOCK(vp, LK_INTERLOCK, p);
1629 		return;
1630 	}
1631 
1632 	if (vp->v_usecount == 1) {
1633 		vp->v_usecount--;
1634 		/*
1635 		 * We must call VOP_INACTIVE with the node locked.
1636 		 * If we are doing a vpu, the node is already locked,
1637 		 * so we just need to release the vnode mutex.
1638 		 */
1639 		simple_unlock(&vp->v_interlock);
1640 		VOP_INACTIVE(vp, p);
1641 		if (VSHOULDFREE(vp))
1642 			vfree(vp);
1643 		else
1644 			vlruvp(vp);
1645 	} else {
1646 #ifdef DIAGNOSTIC
1647 		vprint("vput: negative ref count", vp);
1648 #endif
1649 		panic("vput: negative ref cnt");
1650 	}
1651 }
1652 
1653 /*
1654  * Somebody doesn't want the vnode recycled.
1655  */
1656 void
1657 vhold(vp)
1658 	register struct vnode *vp;
1659 {
1660 	int s;
1661 
1662   	s = splbio();
1663 	vp->v_holdcnt++;
1664 	if (VSHOULDBUSY(vp))
1665 		vbusy(vp);
1666 	splx(s);
1667 }
1668 
1669 /*
1670  * One less who cares about this vnode.
1671  */
1672 void
1673 vdrop(vp)
1674 	register struct vnode *vp;
1675 {
1676 	int s;
1677 
1678 	s = splbio();
1679 	if (vp->v_holdcnt <= 0)
1680 		panic("vdrop: holdcnt");
1681 	vp->v_holdcnt--;
1682 	if (VSHOULDFREE(vp))
1683 		vfree(vp);
1684 	splx(s);
1685 }
1686 
1687 /*
1688  * Remove any vnodes in the vnode table belonging to mount point mp.
1689  *
1690  * If FORCECLOSE is not specified, there should not be any active ones,
1691  * return error if any are found (nb: this is a user error, not a
1692  * system error). If FORCECLOSE is specified, detach any active vnodes
1693  * that are found.
1694  *
1695  * If WRITECLOSE is set, only flush out regular file vnodes open for
1696  * writing.
1697  *
1698  * SKIPSYSTEM causes any vnodes marked VSYSTEM to be skipped.
1699  *
1700  * `rootrefs' specifies the base reference count for the root vnode
1701  * of this filesystem. The root vnode is considered busy if its
1702  * v_usecount exceeds this value. On a successful return, vflush()
1703  * will call vrele() on the root vnode exactly rootrefs times.
1704  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
1705  * be zero.
1706  */
1707 #ifdef DIAGNOSTIC
1708 static int busyprt = 0;		/* print out busy vnodes */
1709 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
1710 #endif
1711 
1712 int
1713 vflush(mp, rootrefs, flags)
1714 	struct mount *mp;
1715 	int rootrefs;
1716 	int flags;
1717 {
1718 	struct proc *p = curproc;	/* XXX */
1719 	struct vnode *vp, *nvp, *rootvp = NULL;
1720 	struct vattr vattr;
1721 	int busy = 0, error;
1722 
1723 	if (rootrefs > 0) {
1724 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
1725 		    ("vflush: bad args"));
1726 		/*
1727 		 * Get the filesystem root vnode. We can vput() it
1728 		 * immediately, since with rootrefs > 0, it won't go away.
1729 		 */
1730 		if ((error = VFS_ROOT(mp, &rootvp)) != 0)
1731 			return (error);
1732 		vput(rootvp);
1733 	}
1734 	simple_lock(&mntvnode_slock);
1735 loop:
1736 	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp; vp = nvp) {
1737 		/*
1738 		 * Make sure this vnode wasn't reclaimed in getnewvnode().
1739 		 * Start over if it has (it won't be on the list anymore).
1740 		 */
1741 		if (vp->v_mount != mp)
1742 			goto loop;
1743 		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1744 
1745 		simple_lock(&vp->v_interlock);
1746 		/*
1747 		 * Skip over a vnodes marked VSYSTEM.
1748 		 */
1749 		if ((flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1750 			simple_unlock(&vp->v_interlock);
1751 			continue;
1752 		}
1753 		/*
1754 		 * If WRITECLOSE is set, flush out unlinked but still open
1755 		 * files (even if open only for reading) and regular file
1756 		 * vnodes open for writing.
1757 		 */
1758 		if ((flags & WRITECLOSE) &&
1759 		    (vp->v_type == VNON ||
1760 		    (VOP_GETATTR(vp, &vattr, p->p_ucred, p) == 0 &&
1761 		    vattr.va_nlink > 0)) &&
1762 		    (vp->v_writecount == 0 || vp->v_type != VREG)) {
1763 			simple_unlock(&vp->v_interlock);
1764 			continue;
1765 		}
1766 
1767 		/*
1768 		 * With v_usecount == 0, all we need to do is clear out the
1769 		 * vnode data structures and we are done.
1770 		 */
1771 		if (vp->v_usecount == 0) {
1772 			simple_unlock(&mntvnode_slock);
1773 			vgonel(vp, p);
1774 			simple_lock(&mntvnode_slock);
1775 			continue;
1776 		}
1777 
1778 		/*
1779 		 * If FORCECLOSE is set, forcibly close the vnode. For block
1780 		 * or character devices, revert to an anonymous device. For
1781 		 * all other files, just kill them.
1782 		 */
1783 		if (flags & FORCECLOSE) {
1784 			simple_unlock(&mntvnode_slock);
1785 			if (vp->v_type != VBLK && vp->v_type != VCHR) {
1786 				vgonel(vp, p);
1787 			} else {
1788 				vclean(vp, 0, p);
1789 				vp->v_op = spec_vnodeop_p;
1790 				insmntque(vp, (struct mount *) 0);
1791 			}
1792 			simple_lock(&mntvnode_slock);
1793 			continue;
1794 		}
1795 #ifdef DIAGNOSTIC
1796 		if (busyprt)
1797 			vprint("vflush: busy vnode", vp);
1798 #endif
1799 		simple_unlock(&vp->v_interlock);
1800 		busy++;
1801 	}
1802 	simple_unlock(&mntvnode_slock);
1803 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
1804 		/*
1805 		 * If just the root vnode is busy, and if its refcount
1806 		 * is equal to `rootrefs', then go ahead and kill it.
1807 		 */
1808 		simple_lock(&rootvp->v_interlock);
1809 		KASSERT(busy > 0, ("vflush: not busy"));
1810 		KASSERT(rootvp->v_usecount >= rootrefs, ("vflush: rootrefs"));
1811 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
1812 			vgonel(rootvp, p);
1813 			busy = 0;
1814 		} else
1815 			simple_unlock(&rootvp->v_interlock);
1816 	}
1817 	if (busy)
1818 		return (EBUSY);
1819 	for (; rootrefs > 0; rootrefs--)
1820 		vrele(rootvp);
1821 	return (0);
1822 }
1823 
1824 /*
1825  * We do not want to recycle the vnode too quickly.
1826  *
1827  * XXX we can't move vp's around the nvnodelist without really screwing
1828  * up the efficiency of filesystem SYNC and friends.  This code is
1829  * disabled until we fix the syncing code's scanning algorithm.
1830  */
1831 static void
1832 vlruvp(struct vnode *vp)
1833 {
1834 #if 0
1835 	struct mount *mp;
1836 
1837 	if ((mp = vp->v_mount) != NULL) {
1838 		simple_lock(&mntvnode_slock);
1839 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1840 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1841 		simple_unlock(&mntvnode_slock);
1842 	}
1843 #endif
1844 }
1845 
1846 /*
1847  * Disassociate the underlying file system from a vnode.
1848  */
1849 static void
1850 vclean(vp, flags, p)
1851 	struct vnode *vp;
1852 	int flags;
1853 	struct proc *p;
1854 {
1855 	int active;
1856 
1857 	/*
1858 	 * Check to see if the vnode is in use. If so we have to reference it
1859 	 * before we clean it out so that its count cannot fall to zero and
1860 	 * generate a race against ourselves to recycle it.
1861 	 */
1862 	if ((active = vp->v_usecount))
1863 		vp->v_usecount++;
1864 
1865 	/*
1866 	 * Prevent the vnode from being recycled or brought into use while we
1867 	 * clean it out.
1868 	 */
1869 	if (vp->v_flag & VXLOCK)
1870 		panic("vclean: deadlock");
1871 	vp->v_flag |= VXLOCK;
1872 	vp->v_vxproc = curproc;
1873 	/*
1874 	 * Even if the count is zero, the VOP_INACTIVE routine may still
1875 	 * have the object locked while it cleans it out. The VOP_LOCK
1876 	 * ensures that the VOP_INACTIVE routine is done with its work.
1877 	 * For active vnodes, it ensures that no other activity can
1878 	 * occur while the underlying object is being cleaned out.
1879 	 */
1880 	VOP_LOCK(vp, LK_DRAIN | LK_INTERLOCK, p);
1881 
1882 	/*
1883 	 * Clean out any buffers associated with the vnode.
1884 	 */
1885 	vinvalbuf(vp, V_SAVE, NOCRED, p, 0, 0);
1886 
1887 	VOP_DESTROYVOBJECT(vp);
1888 
1889 	/*
1890 	 * If purging an active vnode, it must be closed and
1891 	 * deactivated before being reclaimed. Note that the
1892 	 * VOP_INACTIVE will unlock the vnode.
1893 	 */
1894 	if (active) {
1895 		if (flags & DOCLOSE)
1896 			VOP_CLOSE(vp, FNONBLOCK, NOCRED, p);
1897 		VOP_INACTIVE(vp, p);
1898 	} else {
1899 		/*
1900 		 * Any other processes trying to obtain this lock must first
1901 		 * wait for VXLOCK to clear, then call the new lock operation.
1902 		 */
1903 		VOP_UNLOCK(vp, 0, p);
1904 	}
1905 	/*
1906 	 * Reclaim the vnode.
1907 	 */
1908 	if (VOP_RECLAIM(vp, p))
1909 		panic("vclean: cannot reclaim");
1910 
1911 	if (active) {
1912 		/*
1913 		 * Inline copy of vrele() since VOP_INACTIVE
1914 		 * has already been called.
1915 		 */
1916 		simple_lock(&vp->v_interlock);
1917 		if (--vp->v_usecount <= 0) {
1918 #ifdef DIAGNOSTIC
1919 			if (vp->v_usecount < 0 || vp->v_writecount != 0) {
1920 				vprint("vclean: bad ref count", vp);
1921 				panic("vclean: ref cnt");
1922 			}
1923 #endif
1924 			vfree(vp);
1925 		}
1926 		simple_unlock(&vp->v_interlock);
1927 	}
1928 
1929 	cache_purge(vp);
1930 	vp->v_vnlock = NULL;
1931 
1932 	if (VSHOULDFREE(vp))
1933 		vfree(vp);
1934 
1935 	/*
1936 	 * Done with purge, notify sleepers of the grim news.
1937 	 */
1938 	vp->v_op = dead_vnodeop_p;
1939 	vn_pollgone(vp);
1940 	vp->v_tag = VT_NON;
1941 	vp->v_flag &= ~VXLOCK;
1942 	vp->v_vxproc = NULL;
1943 	if (vp->v_flag & VXWANT) {
1944 		vp->v_flag &= ~VXWANT;
1945 		wakeup((caddr_t) vp);
1946 	}
1947 }
1948 
1949 /*
1950  * Eliminate all activity associated with the requested vnode
1951  * and with all vnodes aliased to the requested vnode.
1952  */
1953 int
1954 vop_revoke(ap)
1955 	struct vop_revoke_args /* {
1956 		struct vnode *a_vp;
1957 		int a_flags;
1958 	} */ *ap;
1959 {
1960 	struct vnode *vp, *vq;
1961 	dev_t dev;
1962 
1963 	KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
1964 
1965 	vp = ap->a_vp;
1966 	/*
1967 	 * If a vgone (or vclean) is already in progress,
1968 	 * wait until it is done and return.
1969 	 */
1970 	if (vp->v_flag & VXLOCK) {
1971 		vp->v_flag |= VXWANT;
1972 		simple_unlock(&vp->v_interlock);
1973 		tsleep((caddr_t)vp, PINOD, "vop_revokeall", 0);
1974 		return (0);
1975 	}
1976 	dev = vp->v_rdev;
1977 	for (;;) {
1978 		simple_lock(&spechash_slock);
1979 		vq = SLIST_FIRST(&dev->si_hlist);
1980 		simple_unlock(&spechash_slock);
1981 		if (!vq)
1982 			break;
1983 		vgone(vq);
1984 	}
1985 	return (0);
1986 }
1987 
1988 /*
1989  * Recycle an unused vnode to the front of the free list.
1990  * Release the passed interlock if the vnode will be recycled.
1991  */
1992 int
1993 vrecycle(vp, inter_lkp, p)
1994 	struct vnode *vp;
1995 	struct simplelock *inter_lkp;
1996 	struct proc *p;
1997 {
1998 
1999 	simple_lock(&vp->v_interlock);
2000 	if (vp->v_usecount == 0) {
2001 		if (inter_lkp) {
2002 			simple_unlock(inter_lkp);
2003 		}
2004 		vgonel(vp, p);
2005 		return (1);
2006 	}
2007 	simple_unlock(&vp->v_interlock);
2008 	return (0);
2009 }
2010 
2011 /*
2012  * Eliminate all activity associated with a vnode
2013  * in preparation for reuse.
2014  */
2015 void
2016 vgone(vp)
2017 	register struct vnode *vp;
2018 {
2019 	struct proc *p = curproc;	/* XXX */
2020 
2021 	simple_lock(&vp->v_interlock);
2022 	vgonel(vp, p);
2023 }
2024 
2025 /*
2026  * vgone, with the vp interlock held.
2027  */
2028 void
2029 vgonel(vp, p)
2030 	struct vnode *vp;
2031 	struct proc *p;
2032 {
2033 	int s;
2034 
2035 	/*
2036 	 * If a vgone (or vclean) is already in progress,
2037 	 * wait until it is done and return.
2038 	 */
2039 	if (vp->v_flag & VXLOCK) {
2040 		vp->v_flag |= VXWANT;
2041 		simple_unlock(&vp->v_interlock);
2042 		tsleep((caddr_t)vp, PINOD, "vgone", 0);
2043 		return;
2044 	}
2045 
2046 	/*
2047 	 * Clean out the filesystem specific data.
2048 	 */
2049 	vclean(vp, DOCLOSE, p);
2050 	simple_lock(&vp->v_interlock);
2051 
2052 	/*
2053 	 * Delete from old mount point vnode list, if on one.
2054 	 */
2055 	if (vp->v_mount != NULL)
2056 		insmntque(vp, (struct mount *)0);
2057 	/*
2058 	 * If special device, remove it from special device alias list
2059 	 * if it is on one.
2060 	 */
2061 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
2062 		simple_lock(&spechash_slock);
2063 		SLIST_REMOVE(&vp->v_hashchain, vp, vnode, v_specnext);
2064 		freedev(vp->v_rdev);
2065 		simple_unlock(&spechash_slock);
2066 		vp->v_rdev = NULL;
2067 	}
2068 
2069 	/*
2070 	 * If it is on the freelist and not already at the head,
2071 	 * move it to the head of the list. The test of the
2072 	 * VDOOMED flag and the reference count of zero is because
2073 	 * it will be removed from the free list by getnewvnode,
2074 	 * but will not have its reference count incremented until
2075 	 * after calling vgone. If the reference count were
2076 	 * incremented first, vgone would (incorrectly) try to
2077 	 * close the previous instance of the underlying object.
2078 	 */
2079 	if (vp->v_usecount == 0 && !(vp->v_flag & VDOOMED)) {
2080 		s = splbio();
2081 		simple_lock(&vnode_free_list_slock);
2082 		if (vp->v_flag & VFREE)
2083 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2084 		else
2085 			freevnodes++;
2086 		vp->v_flag |= VFREE;
2087 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2088 		simple_unlock(&vnode_free_list_slock);
2089 		splx(s);
2090 	}
2091 
2092 	vp->v_type = VBAD;
2093 	simple_unlock(&vp->v_interlock);
2094 }
2095 
2096 /*
2097  * Lookup a vnode by device number.
2098  */
2099 int
2100 vfinddev(dev, type, vpp)
2101 	dev_t dev;
2102 	enum vtype type;
2103 	struct vnode **vpp;
2104 {
2105 	struct vnode *vp;
2106 
2107 	simple_lock(&spechash_slock);
2108 	SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2109 		if (type == vp->v_type) {
2110 			*vpp = vp;
2111 			simple_unlock(&spechash_slock);
2112 			return (1);
2113 		}
2114 	}
2115 	simple_unlock(&spechash_slock);
2116 	return (0);
2117 }
2118 
2119 /*
2120  * Calculate the total number of references to a special device.
2121  */
2122 int
2123 vcount(vp)
2124 	struct vnode *vp;
2125 {
2126 	struct vnode *vq;
2127 	int count;
2128 
2129 	count = 0;
2130 	simple_lock(&spechash_slock);
2131 	SLIST_FOREACH(vq, &vp->v_hashchain, v_specnext)
2132 		count += vq->v_usecount;
2133 	simple_unlock(&spechash_slock);
2134 	return (count);
2135 }
2136 
2137 /*
2138  * Same as above, but using the dev_t as argument
2139  */
2140 
2141 int
2142 count_dev(dev)
2143 	dev_t dev;
2144 {
2145 	struct vnode *vp;
2146 
2147 	vp = SLIST_FIRST(&dev->si_hlist);
2148 	if (vp == NULL)
2149 		return (0);
2150 	return(vcount(vp));
2151 }
2152 
2153 /*
2154  * Print out a description of a vnode.
2155  */
2156 static char *typename[] =
2157 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
2158 
2159 void
2160 vprint(label, vp)
2161 	char *label;
2162 	struct vnode *vp;
2163 {
2164 	char buf[96];
2165 
2166 	if (label != NULL)
2167 		printf("%s: %p: ", label, (void *)vp);
2168 	else
2169 		printf("%p: ", (void *)vp);
2170 	printf("type %s, usecount %d, writecount %d, refcount %d,",
2171 	    typename[vp->v_type], vp->v_usecount, vp->v_writecount,
2172 	    vp->v_holdcnt);
2173 	buf[0] = '\0';
2174 	if (vp->v_flag & VROOT)
2175 		strcat(buf, "|VROOT");
2176 	if (vp->v_flag & VTEXT)
2177 		strcat(buf, "|VTEXT");
2178 	if (vp->v_flag & VSYSTEM)
2179 		strcat(buf, "|VSYSTEM");
2180 	if (vp->v_flag & VXLOCK)
2181 		strcat(buf, "|VXLOCK");
2182 	if (vp->v_flag & VXWANT)
2183 		strcat(buf, "|VXWANT");
2184 	if (vp->v_flag & VBWAIT)
2185 		strcat(buf, "|VBWAIT");
2186 	if (vp->v_flag & VDOOMED)
2187 		strcat(buf, "|VDOOMED");
2188 	if (vp->v_flag & VFREE)
2189 		strcat(buf, "|VFREE");
2190 	if (vp->v_flag & VOBJBUF)
2191 		strcat(buf, "|VOBJBUF");
2192 	if (buf[0] != '\0')
2193 		printf(" flags (%s)", &buf[1]);
2194 	if (vp->v_data == NULL) {
2195 		printf("\n");
2196 	} else {
2197 		printf("\n\t");
2198 		VOP_PRINT(vp);
2199 	}
2200 }
2201 
2202 #ifdef DDB
2203 #include <ddb/ddb.h>
2204 /*
2205  * List all of the locked vnodes in the system.
2206  * Called when debugging the kernel.
2207  */
2208 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
2209 {
2210 	struct proc *p = curproc;	/* XXX */
2211 	struct mount *mp, *nmp;
2212 	struct vnode *vp;
2213 
2214 	printf("Locked vnodes\n");
2215 	simple_lock(&mountlist_slock);
2216 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2217 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock, p)) {
2218 			nmp = TAILQ_NEXT(mp, mnt_list);
2219 			continue;
2220 		}
2221 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2222 			if (VOP_ISLOCKED(vp, NULL))
2223 				vprint((char *)0, vp);
2224 		}
2225 		simple_lock(&mountlist_slock);
2226 		nmp = TAILQ_NEXT(mp, mnt_list);
2227 		vfs_unbusy(mp, p);
2228 	}
2229 	simple_unlock(&mountlist_slock);
2230 }
2231 #endif
2232 
2233 /*
2234  * Top level filesystem related information gathering.
2235  */
2236 static int	sysctl_ovfs_conf __P((SYSCTL_HANDLER_ARGS));
2237 
2238 static int
2239 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2240 {
2241 	int *name = (int *)arg1 - 1;	/* XXX */
2242 	u_int namelen = arg2 + 1;	/* XXX */
2243 	struct vfsconf *vfsp;
2244 
2245 #if 1 || defined(COMPAT_PRELITE2)
2246 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2247 	if (namelen == 1)
2248 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2249 #endif
2250 
2251 #ifdef notyet
2252 	/* all sysctl names at this level are at least name and field */
2253 	if (namelen < 2)
2254 		return (ENOTDIR);		/* overloaded */
2255 	if (name[0] != VFS_GENERIC) {
2256 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2257 			if (vfsp->vfc_typenum == name[0])
2258 				break;
2259 		if (vfsp == NULL)
2260 			return (EOPNOTSUPP);
2261 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2262 		    oldp, oldlenp, newp, newlen, p));
2263 	}
2264 #endif
2265 	switch (name[1]) {
2266 	case VFS_MAXTYPENUM:
2267 		if (namelen != 2)
2268 			return (ENOTDIR);
2269 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2270 	case VFS_CONF:
2271 		if (namelen != 3)
2272 			return (ENOTDIR);	/* overloaded */
2273 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2274 			if (vfsp->vfc_typenum == name[2])
2275 				break;
2276 		if (vfsp == NULL)
2277 			return (EOPNOTSUPP);
2278 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
2279 	}
2280 	return (EOPNOTSUPP);
2281 }
2282 
2283 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
2284 	"Generic filesystem");
2285 
2286 #if 1 || defined(COMPAT_PRELITE2)
2287 
2288 static int
2289 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2290 {
2291 	int error;
2292 	struct vfsconf *vfsp;
2293 	struct ovfsconf ovfs;
2294 
2295 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2296 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2297 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2298 		ovfs.vfc_index = vfsp->vfc_typenum;
2299 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2300 		ovfs.vfc_flags = vfsp->vfc_flags;
2301 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2302 		if (error)
2303 			return error;
2304 	}
2305 	return 0;
2306 }
2307 
2308 #endif /* 1 || COMPAT_PRELITE2 */
2309 
2310 #if 0
2311 #define KINFO_VNODESLOP	10
2312 /*
2313  * Dump vnode list (via sysctl).
2314  * Copyout address of vnode followed by vnode.
2315  */
2316 /* ARGSUSED */
2317 static int
2318 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2319 {
2320 	struct proc *p = curproc;	/* XXX */
2321 	struct mount *mp, *nmp;
2322 	struct vnode *nvp, *vp;
2323 	int error;
2324 
2325 #define VPTRSZ	sizeof (struct vnode *)
2326 #define VNODESZ	sizeof (struct vnode)
2327 
2328 	req->lock = 0;
2329 	if (!req->oldptr) /* Make an estimate */
2330 		return (SYSCTL_OUT(req, 0,
2331 			(numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
2332 
2333 	simple_lock(&mountlist_slock);
2334 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2335 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock, p)) {
2336 			nmp = TAILQ_NEXT(mp, mnt_list);
2337 			continue;
2338 		}
2339 again:
2340 		simple_lock(&mntvnode_slock);
2341 		for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2342 		     vp != NULL;
2343 		     vp = nvp) {
2344 			/*
2345 			 * Check that the vp is still associated with
2346 			 * this filesystem.  RACE: could have been
2347 			 * recycled onto the same filesystem.
2348 			 */
2349 			if (vp->v_mount != mp) {
2350 				simple_unlock(&mntvnode_slock);
2351 				goto again;
2352 			}
2353 			nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2354 			simple_unlock(&mntvnode_slock);
2355 			if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
2356 			    (error = SYSCTL_OUT(req, vp, VNODESZ)))
2357 				return (error);
2358 			simple_lock(&mntvnode_slock);
2359 		}
2360 		simple_unlock(&mntvnode_slock);
2361 		simple_lock(&mountlist_slock);
2362 		nmp = TAILQ_NEXT(mp, mnt_list);
2363 		vfs_unbusy(mp, p);
2364 	}
2365 	simple_unlock(&mountlist_slock);
2366 
2367 	return (0);
2368 }
2369 #endif
2370 
2371 /*
2372  * XXX
2373  * Exporting the vnode list on large systems causes them to crash.
2374  * Exporting the vnode list on medium systems causes sysctl to coredump.
2375  */
2376 #if 0
2377 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2378 	0, 0, sysctl_vnode, "S,vnode", "");
2379 #endif
2380 
2381 /*
2382  * Check to see if a filesystem is mounted on a block device.
2383  */
2384 int
2385 vfs_mountedon(vp)
2386 	struct vnode *vp;
2387 {
2388 
2389 	if (vp->v_specmountpoint != NULL)
2390 		return (EBUSY);
2391 	return (0);
2392 }
2393 
2394 /*
2395  * Unmount all filesystems. The list is traversed in reverse order
2396  * of mounting to avoid dependencies.
2397  */
2398 void
2399 vfs_unmountall()
2400 {
2401 	struct mount *mp;
2402 	struct proc *p;
2403 	int error;
2404 
2405 	if (curproc != NULL)
2406 		p = curproc;
2407 	else
2408 		p = initproc;	/* XXX XXX should this be proc0? */
2409 	/*
2410 	 * Since this only runs when rebooting, it is not interlocked.
2411 	 */
2412 	while(!TAILQ_EMPTY(&mountlist)) {
2413 		mp = TAILQ_LAST(&mountlist, mntlist);
2414 		error = dounmount(mp, MNT_FORCE, p);
2415 		if (error) {
2416 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
2417 			printf("unmount of %s failed (",
2418 			    mp->mnt_stat.f_mntonname);
2419 			if (error == EBUSY)
2420 				printf("BUSY)\n");
2421 			else
2422 				printf("%d)\n", error);
2423 		} else {
2424 			/* The unmount has removed mp from the mountlist */
2425 		}
2426 	}
2427 }
2428 
2429 /*
2430  * Build hash lists of net addresses and hang them off the mount point.
2431  * Called by ufs_mount() to set up the lists of export addresses.
2432  */
2433 static int
2434 vfs_hang_addrlist(mp, nep, argp)
2435 	struct mount *mp;
2436 	struct netexport *nep;
2437 	struct export_args *argp;
2438 {
2439 	register struct netcred *np;
2440 	register struct radix_node_head *rnh;
2441 	register int i;
2442 	struct radix_node *rn;
2443 	struct sockaddr *saddr, *smask = 0;
2444 	struct domain *dom;
2445 	int error;
2446 
2447 	if (argp->ex_addrlen == 0) {
2448 		if (mp->mnt_flag & MNT_DEFEXPORTED)
2449 			return (EPERM);
2450 		np = &nep->ne_defexported;
2451 		np->netc_exflags = argp->ex_flags;
2452 		np->netc_anon = argp->ex_anon;
2453 		np->netc_anon.cr_ref = 1;
2454 		mp->mnt_flag |= MNT_DEFEXPORTED;
2455 		return (0);
2456 	}
2457 
2458 	if (argp->ex_addrlen > MLEN)
2459 		return (EINVAL);
2460 
2461 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2462 	np = (struct netcred *) malloc(i, M_NETADDR, M_WAITOK);
2463 	bzero((caddr_t) np, i);
2464 	saddr = (struct sockaddr *) (np + 1);
2465 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2466 		goto out;
2467 	if (saddr->sa_len > argp->ex_addrlen)
2468 		saddr->sa_len = argp->ex_addrlen;
2469 	if (argp->ex_masklen) {
2470 		smask = (struct sockaddr *) ((caddr_t) saddr + argp->ex_addrlen);
2471 		error = copyin(argp->ex_mask, (caddr_t) smask, argp->ex_masklen);
2472 		if (error)
2473 			goto out;
2474 		if (smask->sa_len > argp->ex_masklen)
2475 			smask->sa_len = argp->ex_masklen;
2476 	}
2477 	i = saddr->sa_family;
2478 	if ((rnh = nep->ne_rtable[i]) == 0) {
2479 		/*
2480 		 * Seems silly to initialize every AF when most are not used,
2481 		 * do so on demand here
2482 		 */
2483 		for (dom = domains; dom; dom = dom->dom_next)
2484 			if (dom->dom_family == i && dom->dom_rtattach) {
2485 				dom->dom_rtattach((void **) &nep->ne_rtable[i],
2486 				    dom->dom_rtoffset);
2487 				break;
2488 			}
2489 		if ((rnh = nep->ne_rtable[i]) == 0) {
2490 			error = ENOBUFS;
2491 			goto out;
2492 		}
2493 	}
2494 	rn = (*rnh->rnh_addaddr) ((caddr_t) saddr, (caddr_t) smask, rnh,
2495 	    np->netc_rnodes);
2496 	if (rn == 0 || np != (struct netcred *) rn) {	/* already exists */
2497 		error = EPERM;
2498 		goto out;
2499 	}
2500 	np->netc_exflags = argp->ex_flags;
2501 	np->netc_anon = argp->ex_anon;
2502 	np->netc_anon.cr_ref = 1;
2503 	return (0);
2504 out:
2505 	free(np, M_NETADDR);
2506 	return (error);
2507 }
2508 
2509 /* ARGSUSED */
2510 static int
2511 vfs_free_netcred(rn, w)
2512 	struct radix_node *rn;
2513 	void *w;
2514 {
2515 	register struct radix_node_head *rnh = (struct radix_node_head *) w;
2516 
2517 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2518 	free((caddr_t) rn, M_NETADDR);
2519 	return (0);
2520 }
2521 
2522 /*
2523  * Free the net address hash lists that are hanging off the mount points.
2524  */
2525 static void
2526 vfs_free_addrlist(nep)
2527 	struct netexport *nep;
2528 {
2529 	register int i;
2530 	register struct radix_node_head *rnh;
2531 
2532 	for (i = 0; i <= AF_MAX; i++)
2533 		if ((rnh = nep->ne_rtable[i])) {
2534 			(*rnh->rnh_walktree) (rnh, vfs_free_netcred,
2535 			    (caddr_t) rnh);
2536 			free((caddr_t) rnh, M_RTABLE);
2537 			nep->ne_rtable[i] = 0;
2538 		}
2539 }
2540 
2541 int
2542 vfs_export(mp, nep, argp)
2543 	struct mount *mp;
2544 	struct netexport *nep;
2545 	struct export_args *argp;
2546 {
2547 	int error;
2548 
2549 	if (argp->ex_flags & MNT_DELEXPORT) {
2550 		if (mp->mnt_flag & MNT_EXPUBLIC) {
2551 			vfs_setpublicfs(NULL, NULL, NULL);
2552 			mp->mnt_flag &= ~MNT_EXPUBLIC;
2553 		}
2554 		vfs_free_addrlist(nep);
2555 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2556 	}
2557 	if (argp->ex_flags & MNT_EXPORTED) {
2558 		if (argp->ex_flags & MNT_EXPUBLIC) {
2559 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2560 				return (error);
2561 			mp->mnt_flag |= MNT_EXPUBLIC;
2562 		}
2563 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
2564 			return (error);
2565 		mp->mnt_flag |= MNT_EXPORTED;
2566 	}
2567 	return (0);
2568 }
2569 
2570 
2571 /*
2572  * Set the publicly exported filesystem (WebNFS). Currently, only
2573  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2574  */
2575 int
2576 vfs_setpublicfs(mp, nep, argp)
2577 	struct mount *mp;
2578 	struct netexport *nep;
2579 	struct export_args *argp;
2580 {
2581 	int error;
2582 	struct vnode *rvp;
2583 	char *cp;
2584 
2585 	/*
2586 	 * mp == NULL -> invalidate the current info, the FS is
2587 	 * no longer exported. May be called from either vfs_export
2588 	 * or unmount, so check if it hasn't already been done.
2589 	 */
2590 	if (mp == NULL) {
2591 		if (nfs_pub.np_valid) {
2592 			nfs_pub.np_valid = 0;
2593 			if (nfs_pub.np_index != NULL) {
2594 				FREE(nfs_pub.np_index, M_TEMP);
2595 				nfs_pub.np_index = NULL;
2596 			}
2597 		}
2598 		return (0);
2599 	}
2600 
2601 	/*
2602 	 * Only one allowed at a time.
2603 	 */
2604 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2605 		return (EBUSY);
2606 
2607 	/*
2608 	 * Get real filehandle for root of exported FS.
2609 	 */
2610 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2611 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2612 
2613 	if ((error = VFS_ROOT(mp, &rvp)))
2614 		return (error);
2615 
2616 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2617 		return (error);
2618 
2619 	vput(rvp);
2620 
2621 	/*
2622 	 * If an indexfile was specified, pull it in.
2623 	 */
2624 	if (argp->ex_indexfile != NULL) {
2625 		MALLOC(nfs_pub.np_index, char *, MAXNAMLEN + 1, M_TEMP,
2626 		    M_WAITOK);
2627 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2628 		    MAXNAMLEN, (size_t *)0);
2629 		if (!error) {
2630 			/*
2631 			 * Check for illegal filenames.
2632 			 */
2633 			for (cp = nfs_pub.np_index; *cp; cp++) {
2634 				if (*cp == '/') {
2635 					error = EINVAL;
2636 					break;
2637 				}
2638 			}
2639 		}
2640 		if (error) {
2641 			FREE(nfs_pub.np_index, M_TEMP);
2642 			return (error);
2643 		}
2644 	}
2645 
2646 	nfs_pub.np_mount = mp;
2647 	nfs_pub.np_valid = 1;
2648 	return (0);
2649 }
2650 
2651 struct netcred *
2652 vfs_export_lookup(mp, nep, nam)
2653 	register struct mount *mp;
2654 	struct netexport *nep;
2655 	struct sockaddr *nam;
2656 {
2657 	register struct netcred *np;
2658 	register struct radix_node_head *rnh;
2659 	struct sockaddr *saddr;
2660 
2661 	np = NULL;
2662 	if (mp->mnt_flag & MNT_EXPORTED) {
2663 		/*
2664 		 * Lookup in the export list first.
2665 		 */
2666 		if (nam != NULL) {
2667 			saddr = nam;
2668 			rnh = nep->ne_rtable[saddr->sa_family];
2669 			if (rnh != NULL) {
2670 				np = (struct netcred *)
2671 					(*rnh->rnh_matchaddr)((caddr_t)saddr,
2672 							      rnh);
2673 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2674 					np = NULL;
2675 			}
2676 		}
2677 		/*
2678 		 * If no address match, use the default if it exists.
2679 		 */
2680 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2681 			np = &nep->ne_defexported;
2682 	}
2683 	return (np);
2684 }
2685 
2686 /*
2687  * perform msync on all vnodes under a mount point
2688  * the mount point must be locked.
2689  */
2690 void
2691 vfs_msync(struct mount *mp, int flags)
2692 {
2693 	struct vnode *vp, *nvp;
2694 	struct vm_object *obj;
2695 	int tries;
2696 
2697 	tries = 5;
2698 	simple_lock(&mntvnode_slock);
2699 loop:
2700 	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp != NULL; vp = nvp) {
2701 		if (vp->v_mount != mp) {
2702 			if (--tries > 0)
2703 				goto loop;
2704 			break;
2705 		}
2706 		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2707 
2708 		if (vp->v_flag & VXLOCK)	/* XXX: what if MNT_WAIT? */
2709 			continue;
2710 
2711 		/*
2712 		 * There could be hundreds of thousands of vnodes, we cannot
2713 		 * afford to do anything heavy-weight until we have a fairly
2714 		 * good indication that there is something to do.
2715 		 */
2716 		if ((vp->v_flag & VOBJDIRTY) &&
2717 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2718 			simple_unlock(&mntvnode_slock);
2719 			if (!vget(vp,
2720 			    LK_EXCLUSIVE | LK_RETRY | LK_NOOBJ, curproc)) {
2721 				if (VOP_GETVOBJECT(vp, &obj) == 0) {
2722 					vm_object_page_clean(obj, 0, 0, flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2723 				}
2724 				vput(vp);
2725 			}
2726 			simple_lock(&mntvnode_slock);
2727 			if (TAILQ_NEXT(vp, v_nmntvnodes) != nvp) {
2728 				if (--tries > 0)
2729 					goto loop;
2730 				break;
2731 			}
2732 		}
2733 	}
2734 	simple_unlock(&mntvnode_slock);
2735 }
2736 
2737 /*
2738  * Create the VM object needed for VMIO and mmap support.  This
2739  * is done for all VREG files in the system.  Some filesystems might
2740  * afford the additional metadata buffering capability of the
2741  * VMIO code by making the device node be VMIO mode also.
2742  *
2743  * vp must be locked when vfs_object_create is called.
2744  */
2745 int
2746 vfs_object_create(vp, p, cred)
2747 	struct vnode *vp;
2748 	struct proc *p;
2749 	struct ucred *cred;
2750 {
2751 	return (VOP_CREATEVOBJECT(vp, cred, p));
2752 }
2753 
2754 void
2755 vfree(vp)
2756 	struct vnode *vp;
2757 {
2758 	int s;
2759 
2760 	s = splbio();
2761 	simple_lock(&vnode_free_list_slock);
2762 	KASSERT((vp->v_flag & VFREE) == 0, ("vnode already free"));
2763 	if (vp->v_flag & VAGE) {
2764 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2765 	} else {
2766 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2767 	}
2768 	freevnodes++;
2769 	simple_unlock(&vnode_free_list_slock);
2770 	vp->v_flag &= ~VAGE;
2771 	vp->v_flag |= VFREE;
2772 	splx(s);
2773 }
2774 
2775 void
2776 vbusy(vp)
2777 	struct vnode *vp;
2778 {
2779 	int s;
2780 
2781 	s = splbio();
2782 	simple_lock(&vnode_free_list_slock);
2783 	KASSERT((vp->v_flag & VFREE) != 0, ("vnode not free"));
2784 	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2785 	freevnodes--;
2786 	simple_unlock(&vnode_free_list_slock);
2787 	vp->v_flag &= ~(VFREE|VAGE);
2788 	splx(s);
2789 }
2790 
2791 /*
2792  * Record a process's interest in events which might happen to
2793  * a vnode.  Because poll uses the historic select-style interface
2794  * internally, this routine serves as both the ``check for any
2795  * pending events'' and the ``record my interest in future events''
2796  * functions.  (These are done together, while the lock is held,
2797  * to avoid race conditions.)
2798  */
2799 int
2800 vn_pollrecord(vp, p, events)
2801 	struct vnode *vp;
2802 	struct proc *p;
2803 	short events;
2804 {
2805 	simple_lock(&vp->v_pollinfo.vpi_lock);
2806 	if (vp->v_pollinfo.vpi_revents & events) {
2807 		/*
2808 		 * This leaves events we are not interested
2809 		 * in available for the other process which
2810 		 * which presumably had requested them
2811 		 * (otherwise they would never have been
2812 		 * recorded).
2813 		 */
2814 		events &= vp->v_pollinfo.vpi_revents;
2815 		vp->v_pollinfo.vpi_revents &= ~events;
2816 
2817 		simple_unlock(&vp->v_pollinfo.vpi_lock);
2818 		return events;
2819 	}
2820 	vp->v_pollinfo.vpi_events |= events;
2821 	selrecord(p, &vp->v_pollinfo.vpi_selinfo);
2822 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2823 	return 0;
2824 }
2825 
2826 /*
2827  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2828  * it is possible for us to miss an event due to race conditions, but
2829  * that condition is expected to be rare, so for the moment it is the
2830  * preferred interface.
2831  */
2832 void
2833 vn_pollevent(vp, events)
2834 	struct vnode *vp;
2835 	short events;
2836 {
2837 	simple_lock(&vp->v_pollinfo.vpi_lock);
2838 	if (vp->v_pollinfo.vpi_events & events) {
2839 		/*
2840 		 * We clear vpi_events so that we don't
2841 		 * call selwakeup() twice if two events are
2842 		 * posted before the polling process(es) is
2843 		 * awakened.  This also ensures that we take at
2844 		 * most one selwakeup() if the polling process
2845 		 * is no longer interested.  However, it does
2846 		 * mean that only one event can be noticed at
2847 		 * a time.  (Perhaps we should only clear those
2848 		 * event bits which we note?) XXX
2849 		 */
2850 		vp->v_pollinfo.vpi_events = 0;	/* &= ~events ??? */
2851 		vp->v_pollinfo.vpi_revents |= events;
2852 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2853 	}
2854 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2855 }
2856 
2857 /*
2858  * Wake up anyone polling on vp because it is being revoked.
2859  * This depends on dead_poll() returning POLLHUP for correct
2860  * behavior.
2861  */
2862 void
2863 vn_pollgone(vp)
2864 	struct vnode *vp;
2865 {
2866 	simple_lock(&vp->v_pollinfo.vpi_lock);
2867 	if (vp->v_pollinfo.vpi_events) {
2868 		vp->v_pollinfo.vpi_events = 0;
2869 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2870 	}
2871 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2872 }
2873 
2874 
2875 
2876 /*
2877  * Routine to create and manage a filesystem syncer vnode.
2878  */
2879 #define sync_close ((int (*) __P((struct  vop_close_args *)))nullop)
2880 static int	sync_fsync __P((struct  vop_fsync_args *));
2881 static int	sync_inactive __P((struct  vop_inactive_args *));
2882 static int	sync_reclaim  __P((struct  vop_reclaim_args *));
2883 #define sync_lock ((int (*) __P((struct  vop_lock_args *)))vop_nolock)
2884 #define sync_unlock ((int (*) __P((struct  vop_unlock_args *)))vop_nounlock)
2885 static int	sync_print __P((struct vop_print_args *));
2886 #define sync_islocked ((int(*) __P((struct vop_islocked_args *)))vop_noislocked)
2887 
2888 static vop_t **sync_vnodeop_p;
2889 static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
2890 	{ &vop_default_desc,	(vop_t *) vop_eopnotsupp },
2891 	{ &vop_close_desc,	(vop_t *) sync_close },		/* close */
2892 	{ &vop_fsync_desc,	(vop_t *) sync_fsync },		/* fsync */
2893 	{ &vop_inactive_desc,	(vop_t *) sync_inactive },	/* inactive */
2894 	{ &vop_reclaim_desc,	(vop_t *) sync_reclaim },	/* reclaim */
2895 	{ &vop_lock_desc,	(vop_t *) sync_lock },		/* lock */
2896 	{ &vop_unlock_desc,	(vop_t *) sync_unlock },	/* unlock */
2897 	{ &vop_print_desc,	(vop_t *) sync_print },		/* print */
2898 	{ &vop_islocked_desc,	(vop_t *) sync_islocked },	/* islocked */
2899 	{ NULL, NULL }
2900 };
2901 static struct vnodeopv_desc sync_vnodeop_opv_desc =
2902 	{ &sync_vnodeop_p, sync_vnodeop_entries };
2903 
2904 VNODEOP_SET(sync_vnodeop_opv_desc);
2905 
2906 /*
2907  * Create a new filesystem syncer vnode for the specified mount point.
2908  */
2909 int
2910 vfs_allocate_syncvnode(mp)
2911 	struct mount *mp;
2912 {
2913 	struct vnode *vp;
2914 	static long start, incr, next;
2915 	int error;
2916 
2917 	/* Allocate a new vnode */
2918 	if ((error = getnewvnode(VT_VFS, mp, sync_vnodeop_p, &vp)) != 0) {
2919 		mp->mnt_syncer = NULL;
2920 		return (error);
2921 	}
2922 	vp->v_type = VNON;
2923 	/*
2924 	 * Place the vnode onto the syncer worklist. We attempt to
2925 	 * scatter them about on the list so that they will go off
2926 	 * at evenly distributed times even if all the filesystems
2927 	 * are mounted at once.
2928 	 */
2929 	next += incr;
2930 	if (next == 0 || next > syncer_maxdelay) {
2931 		start /= 2;
2932 		incr /= 2;
2933 		if (start == 0) {
2934 			start = syncer_maxdelay / 2;
2935 			incr = syncer_maxdelay;
2936 		}
2937 		next = start;
2938 	}
2939 	vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
2940 	mp->mnt_syncer = vp;
2941 	return (0);
2942 }
2943 
2944 /*
2945  * Do a lazy sync of the filesystem.
2946  */
2947 static int
2948 sync_fsync(ap)
2949 	struct vop_fsync_args /* {
2950 		struct vnode *a_vp;
2951 		struct ucred *a_cred;
2952 		int a_waitfor;
2953 		struct proc *a_p;
2954 	} */ *ap;
2955 {
2956 	struct vnode *syncvp = ap->a_vp;
2957 	struct mount *mp = syncvp->v_mount;
2958 	struct proc *p = ap->a_p;
2959 	int asyncflag;
2960 
2961 	/*
2962 	 * We only need to do something if this is a lazy evaluation.
2963 	 */
2964 	if (ap->a_waitfor != MNT_LAZY)
2965 		return (0);
2966 
2967 	/*
2968 	 * Move ourselves to the back of the sync list.
2969 	 */
2970 	vn_syncer_add_to_worklist(syncvp, syncdelay);
2971 
2972 	/*
2973 	 * Walk the list of vnodes pushing all that are dirty and
2974 	 * not already on the sync list.
2975 	 */
2976 	simple_lock(&mountlist_slock);
2977 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_slock, p) != 0) {
2978 		simple_unlock(&mountlist_slock);
2979 		return (0);
2980 	}
2981 	asyncflag = mp->mnt_flag & MNT_ASYNC;
2982 	mp->mnt_flag &= ~MNT_ASYNC;
2983 	vfs_msync(mp, MNT_NOWAIT);
2984 	VFS_SYNC(mp, MNT_LAZY, ap->a_cred, p);
2985 	if (asyncflag)
2986 		mp->mnt_flag |= MNT_ASYNC;
2987 	vfs_unbusy(mp, p);
2988 	return (0);
2989 }
2990 
2991 /*
2992  * The syncer vnode is no referenced.
2993  */
2994 static int
2995 sync_inactive(ap)
2996 	struct vop_inactive_args /* {
2997 		struct vnode *a_vp;
2998 		struct proc *a_p;
2999 	} */ *ap;
3000 {
3001 
3002 	vgone(ap->a_vp);
3003 	return (0);
3004 }
3005 
3006 /*
3007  * The syncer vnode is no longer needed and is being decommissioned.
3008  *
3009  * Modifications to the worklist must be protected at splbio().
3010  */
3011 static int
3012 sync_reclaim(ap)
3013 	struct vop_reclaim_args /* {
3014 		struct vnode *a_vp;
3015 	} */ *ap;
3016 {
3017 	struct vnode *vp = ap->a_vp;
3018 	int s;
3019 
3020 	s = splbio();
3021 	vp->v_mount->mnt_syncer = NULL;
3022 	if (vp->v_flag & VONWORKLST) {
3023 		LIST_REMOVE(vp, v_synclist);
3024 		vp->v_flag &= ~VONWORKLST;
3025 	}
3026 	splx(s);
3027 
3028 	return (0);
3029 }
3030 
3031 /*
3032  * Print out a syncer vnode.
3033  */
3034 static int
3035 sync_print(ap)
3036 	struct vop_print_args /* {
3037 		struct vnode *a_vp;
3038 	} */ *ap;
3039 {
3040 	struct vnode *vp = ap->a_vp;
3041 
3042 	printf("syncer vnode");
3043 	if (vp->v_vnlock != NULL)
3044 		lockmgr_printinfo(vp->v_vnlock);
3045 	printf("\n");
3046 	return (0);
3047 }
3048 
3049 /*
3050  * extract the dev_t from a VBLK or VCHR
3051  */
3052 dev_t
3053 vn_todev(vp)
3054 	struct vnode *vp;
3055 {
3056 	if (vp->v_type != VBLK && vp->v_type != VCHR)
3057 		return (NODEV);
3058 	return (vp->v_rdev);
3059 }
3060 
3061 /*
3062  * Check if vnode represents a disk device
3063  */
3064 int
3065 vn_isdisk(vp, errp)
3066 	struct vnode *vp;
3067 	int *errp;
3068 {
3069 	if (vp->v_type != VBLK && vp->v_type != VCHR) {
3070 		if (errp != NULL)
3071 			*errp = ENOTBLK;
3072 		return (0);
3073 	}
3074 	if (vp->v_rdev == NULL) {
3075 		if (errp != NULL)
3076 			*errp = ENXIO;
3077 		return (0);
3078 	}
3079 	if (!devsw(vp->v_rdev)) {
3080 		if (errp != NULL)
3081 			*errp = ENXIO;
3082 		return (0);
3083 	}
3084 	if (!(devsw(vp->v_rdev)->d_flags & D_DISK)) {
3085 		if (errp != NULL)
3086 			*errp = ENOTBLK;
3087 		return (0);
3088 	}
3089 	if (errp != NULL)
3090 		*errp = 0;
3091 	return (1);
3092 }
3093 
3094 void
3095 NDFREE(ndp, flags)
3096      struct nameidata *ndp;
3097      const uint flags;
3098 {
3099 	if (!(flags & NDF_NO_FREE_PNBUF) &&
3100 	    (ndp->ni_cnd.cn_flags & HASBUF)) {
3101 		zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
3102 		ndp->ni_cnd.cn_flags &= ~HASBUF;
3103 	}
3104 	if (!(flags & NDF_NO_DVP_UNLOCK) &&
3105 	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
3106 	    ndp->ni_dvp != ndp->ni_vp)
3107 		VOP_UNLOCK(ndp->ni_dvp, 0, ndp->ni_cnd.cn_proc);
3108 	if (!(flags & NDF_NO_DVP_RELE) &&
3109 	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
3110 		vrele(ndp->ni_dvp);
3111 		ndp->ni_dvp = NULL;
3112 	}
3113 	if (!(flags & NDF_NO_VP_UNLOCK) &&
3114 	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
3115 		VOP_UNLOCK(ndp->ni_vp, 0, ndp->ni_cnd.cn_proc);
3116 	if (!(flags & NDF_NO_VP_RELE) &&
3117 	    ndp->ni_vp) {
3118 		vrele(ndp->ni_vp);
3119 		ndp->ni_vp = NULL;
3120 	}
3121 	if (!(flags & NDF_NO_STARTDIR_RELE) &&
3122 	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
3123 		vrele(ndp->ni_startdir);
3124 		ndp->ni_startdir = NULL;
3125 	}
3126 }
3127