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