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