xref: /freebsd/sys/kern/vfs_subr.c (revision 0bb263df82e129f5f8c82da6deb55dfe10daa677)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
35  */
36 
37 /*
38  * External virtual filesystem routines
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_ddb.h"
45 #include "opt_mac.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/event.h>
54 #include <sys/eventhandler.h>
55 #include <sys/extattr.h>
56 #include <sys/file.h>
57 #include <sys/fcntl.h>
58 #include <sys/jail.h>
59 #include <sys/kdb.h>
60 #include <sys/kernel.h>
61 #include <sys/kthread.h>
62 #include <sys/malloc.h>
63 #include <sys/mount.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/reboot.h>
67 #include <sys/sleepqueue.h>
68 #include <sys/stat.h>
69 #include <sys/sysctl.h>
70 #include <sys/syslog.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 
74 #include <machine/stdarg.h>
75 
76 #include <security/mac/mac_framework.h>
77 
78 #include <vm/vm.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_extern.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_kern.h>
85 #include <vm/uma.h>
86 
87 #ifdef DDB
88 #include <ddb/ddb.h>
89 #endif
90 
91 static MALLOC_DEFINE(M_NETADDR, "subr_export_host", "Export host address structure");
92 
93 static void	delmntque(struct vnode *vp);
94 static int	flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
95 		    int slpflag, int slptimeo);
96 static void	syncer_shutdown(void *arg, int howto);
97 static int	vtryrecycle(struct vnode *vp);
98 static void	vbusy(struct vnode *vp);
99 static void	vinactive(struct vnode *, struct thread *);
100 static void	v_incr_usecount(struct vnode *);
101 static void	v_decr_usecount(struct vnode *);
102 static void	v_decr_useonly(struct vnode *);
103 static void	v_upgrade_usecount(struct vnode *);
104 static void	vfree(struct vnode *);
105 static void	vnlru_free(int);
106 static void	vdestroy(struct vnode *);
107 static void	vgonel(struct vnode *);
108 static void	vfs_knllock(void *arg);
109 static void	vfs_knlunlock(void *arg);
110 static int	vfs_knllocked(void *arg);
111 
112 
113 /*
114  * Enable Giant pushdown based on whether or not the vm is mpsafe in this
115  * build.  Without mpsafevm the buffer cache can not run Giant free.
116  */
117 int mpsafe_vfs = 1;
118 TUNABLE_INT("debug.mpsafevfs", &mpsafe_vfs);
119 SYSCTL_INT(_debug, OID_AUTO, mpsafevfs, CTLFLAG_RD, &mpsafe_vfs, 0,
120     "MPSAFE VFS");
121 
122 /*
123  * Number of vnodes in existence.  Increased whenever getnewvnode()
124  * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
125  * vnode.
126  */
127 static unsigned long	numvnodes;
128 
129 SYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
130 
131 /*
132  * Conversion tables for conversion from vnode types to inode formats
133  * and back.
134  */
135 enum vtype iftovt_tab[16] = {
136 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
137 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
138 };
139 int vttoif_tab[10] = {
140 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
141 	S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
142 };
143 
144 /*
145  * List of vnodes that are ready for recycling.
146  */
147 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
148 
149 /*
150  * Free vnode target.  Free vnodes may simply be files which have been stat'd
151  * but not read.  This is somewhat common, and a small cache of such files
152  * should be kept to avoid recreation costs.
153  */
154 static u_long wantfreevnodes;
155 SYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
156 /* Number of vnodes in the free list. */
157 static u_long freevnodes;
158 SYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
159 
160 /*
161  * Various variables used for debugging the new implementation of
162  * reassignbuf().
163  * XXX these are probably of (very) limited utility now.
164  */
165 static int reassignbufcalls;
166 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
167 
168 /*
169  * Cache for the mount type id assigned to NFS.  This is used for
170  * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
171  */
172 int	nfs_mount_type = -1;
173 
174 /* To keep more than one thread at a time from running vfs_getnewfsid */
175 static struct mtx mntid_mtx;
176 
177 /*
178  * Lock for any access to the following:
179  *	vnode_free_list
180  *	numvnodes
181  *	freevnodes
182  */
183 static struct mtx vnode_free_list_mtx;
184 
185 /* Publicly exported FS */
186 struct nfs_public nfs_pub;
187 
188 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
189 static uma_zone_t vnode_zone;
190 static uma_zone_t vnodepoll_zone;
191 
192 /* Set to 1 to print out reclaim of active vnodes */
193 int	prtactive;
194 
195 /*
196  * The workitem queue.
197  *
198  * It is useful to delay writes of file data and filesystem metadata
199  * for tens of seconds so that quickly created and deleted files need
200  * not waste disk bandwidth being created and removed. To realize this,
201  * we append vnodes to a "workitem" queue. When running with a soft
202  * updates implementation, most pending metadata dependencies should
203  * not wait for more than a few seconds. Thus, mounted on block devices
204  * are delayed only about a half the time that file data is delayed.
205  * Similarly, directory updates are more critical, so are only delayed
206  * about a third the time that file data is delayed. Thus, there are
207  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
208  * one each second (driven off the filesystem syncer process). The
209  * syncer_delayno variable indicates the next queue that is to be processed.
210  * Items that need to be processed soon are placed in this queue:
211  *
212  *	syncer_workitem_pending[syncer_delayno]
213  *
214  * A delay of fifteen seconds is done by placing the request fifteen
215  * entries later in the queue:
216  *
217  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
218  *
219  */
220 static int syncer_delayno;
221 static long syncer_mask;
222 LIST_HEAD(synclist, bufobj);
223 static struct synclist *syncer_workitem_pending;
224 /*
225  * The sync_mtx protects:
226  *	bo->bo_synclist
227  *	sync_vnode_count
228  *	syncer_delayno
229  *	syncer_state
230  *	syncer_workitem_pending
231  *	syncer_worklist_len
232  *	rushjob
233  */
234 static struct mtx sync_mtx;
235 
236 #define SYNCER_MAXDELAY		32
237 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
238 static int syncdelay = 30;		/* max time to delay syncing data */
239 static int filedelay = 30;		/* time to delay syncing files */
240 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
241 static int dirdelay = 29;		/* time to delay syncing directories */
242 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
243 static int metadelay = 28;		/* time to delay syncing metadata */
244 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
245 static int rushjob;		/* number of slots to run ASAP */
246 static int stat_rush_requests;	/* number of times I/O speeded up */
247 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
248 
249 /*
250  * When shutting down the syncer, run it at four times normal speed.
251  */
252 #define SYNCER_SHUTDOWN_SPEEDUP		4
253 static int sync_vnode_count;
254 static int syncer_worklist_len;
255 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
256     syncer_state;
257 
258 /*
259  * Number of vnodes we want to exist at any one time.  This is mostly used
260  * to size hash tables in vnode-related code.  It is normally not used in
261  * getnewvnode(), as wantfreevnodes is normally nonzero.)
262  *
263  * XXX desiredvnodes is historical cruft and should not exist.
264  */
265 int desiredvnodes;
266 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
267     &desiredvnodes, 0, "Maximum number of vnodes");
268 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
269     &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
270 static int vnlru_nowhere;
271 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
272     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
273 
274 /*
275  * Macros to control when a vnode is freed and recycled.  All require
276  * the vnode interlock.
277  */
278 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
279 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
280 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
281 
282 
283 /*
284  * Initialize the vnode management data structures.
285  */
286 #ifndef	MAXVNODES_MAX
287 #define	MAXVNODES_MAX	100000
288 #endif
289 static void
290 vntblinit(void *dummy __unused)
291 {
292 
293 	/*
294 	 * Desiredvnodes is a function of the physical memory size and
295 	 * the kernel's heap size.  Specifically, desiredvnodes scales
296 	 * in proportion to the physical memory size until two fifths
297 	 * of the kernel's heap size is consumed by vnodes and vm
298 	 * objects.
299 	 */
300 	desiredvnodes = min(maxproc + cnt.v_page_count / 4, 2 * vm_kmem_size /
301 	    (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
302 	if (desiredvnodes > MAXVNODES_MAX) {
303 		if (bootverbose)
304 			printf("Reducing kern.maxvnodes %d -> %d\n",
305 			    desiredvnodes, MAXVNODES_MAX);
306 		desiredvnodes = MAXVNODES_MAX;
307 	}
308 	wantfreevnodes = desiredvnodes / 4;
309 	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
310 	TAILQ_INIT(&vnode_free_list);
311 	mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
312 	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
313 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
314 	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
315 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
316 	/*
317 	 * Initialize the filesystem syncer.
318 	 */
319 	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
320 		&syncer_mask);
321 	syncer_maxdelay = syncer_mask + 1;
322 	mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
323 }
324 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL)
325 
326 
327 /*
328  * Mark a mount point as busy. Used to synchronize access and to delay
329  * unmounting. Interlock is not released on failure.
330  */
331 int
332 vfs_busy(struct mount *mp, int flags, struct mtx *interlkp,
333     struct thread *td)
334 {
335 	int lkflags;
336 
337 	MNT_ILOCK(mp);
338 	MNT_REF(mp);
339 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
340 		if (flags & LK_NOWAIT) {
341 			MNT_REL(mp);
342 			MNT_IUNLOCK(mp);
343 			return (ENOENT);
344 		}
345 		if (interlkp)
346 			mtx_unlock(interlkp);
347 		mp->mnt_kern_flag |= MNTK_MWAIT;
348 		/*
349 		 * Since all busy locks are shared except the exclusive
350 		 * lock granted when unmounting, the only place that a
351 		 * wakeup needs to be done is at the release of the
352 		 * exclusive lock at the end of dounmount.
353 		 */
354 		msleep(mp, MNT_MTX(mp), PVFS, "vfs_busy", 0);
355 		MNT_REL(mp);
356 		MNT_IUNLOCK(mp);
357 		if (interlkp)
358 			mtx_lock(interlkp);
359 		return (ENOENT);
360 	}
361 	if (interlkp)
362 		mtx_unlock(interlkp);
363 	lkflags = LK_SHARED | LK_INTERLOCK;
364 	if (lockmgr(&mp->mnt_lock, lkflags, MNT_MTX(mp), td))
365 		panic("vfs_busy: unexpected lock failure");
366 	return (0);
367 }
368 
369 /*
370  * Free a busy filesystem.
371  */
372 void
373 vfs_unbusy(struct mount *mp, struct thread *td)
374 {
375 
376 	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
377 	vfs_rel(mp);
378 }
379 
380 /*
381  * Lookup a mount point by filesystem identifier.
382  */
383 struct mount *
384 vfs_getvfs(fsid_t *fsid)
385 {
386 	struct mount *mp;
387 
388 	mtx_lock(&mountlist_mtx);
389 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
390 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
391 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
392 			vfs_ref(mp);
393 			mtx_unlock(&mountlist_mtx);
394 			return (mp);
395 		}
396 	}
397 	mtx_unlock(&mountlist_mtx);
398 	return ((struct mount *) 0);
399 }
400 
401 /*
402  * Check if a user can access privileged mount options.
403  */
404 int
405 vfs_suser(struct mount *mp, struct thread *td)
406 {
407 	int error;
408 
409 	/*
410 	 * If the thread is jailed, but this is not a jail-friendly file
411 	 * system, deny immediately.
412 	 */
413 	if (jailed(td->td_ucred) && !(mp->mnt_vfc->vfc_flags & VFCF_JAIL))
414 		return (EPERM);
415 
416 	/*
417 	 * If the file system was mounted outside a jail and a jailed thread
418 	 * tries to access it, deny immediately.
419 	 */
420 	if (!jailed(mp->mnt_cred) && jailed(td->td_ucred))
421 		return (EPERM);
422 
423 	/*
424 	 * If the file system was mounted inside different jail that the jail of
425 	 * the calling thread, deny immediately.
426 	 */
427 	if (jailed(mp->mnt_cred) && jailed(td->td_ucred) &&
428 	    mp->mnt_cred->cr_prison != td->td_ucred->cr_prison) {
429 		return (EPERM);
430 	}
431 
432 	if ((mp->mnt_flag & MNT_USER) == 0 ||
433 	    mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
434 		if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
435 			return (error);
436 	}
437 	return (0);
438 }
439 
440 /*
441  * Get a new unique fsid.  Try to make its val[0] unique, since this value
442  * will be used to create fake device numbers for stat().  Also try (but
443  * not so hard) make its val[0] unique mod 2^16, since some emulators only
444  * support 16-bit device numbers.  We end up with unique val[0]'s for the
445  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
446  *
447  * Keep in mind that several mounts may be running in parallel.  Starting
448  * the search one past where the previous search terminated is both a
449  * micro-optimization and a defense against returning the same fsid to
450  * different mounts.
451  */
452 void
453 vfs_getnewfsid(struct mount *mp)
454 {
455 	static u_int16_t mntid_base;
456 	struct mount *nmp;
457 	fsid_t tfsid;
458 	int mtype;
459 
460 	mtx_lock(&mntid_mtx);
461 	mtype = mp->mnt_vfc->vfc_typenum;
462 	tfsid.val[1] = mtype;
463 	mtype = (mtype & 0xFF) << 24;
464 	for (;;) {
465 		tfsid.val[0] = makedev(255,
466 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
467 		mntid_base++;
468 		if ((nmp = vfs_getvfs(&tfsid)) == NULL)
469 			break;
470 		vfs_rel(nmp);
471 	}
472 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
473 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
474 	mtx_unlock(&mntid_mtx);
475 }
476 
477 /*
478  * Knob to control the precision of file timestamps:
479  *
480  *   0 = seconds only; nanoseconds zeroed.
481  *   1 = seconds and nanoseconds, accurate within 1/HZ.
482  *   2 = seconds and nanoseconds, truncated to microseconds.
483  * >=3 = seconds and nanoseconds, maximum precision.
484  */
485 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
486 
487 static int timestamp_precision = TSP_SEC;
488 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
489     &timestamp_precision, 0, "");
490 
491 /*
492  * Get a current timestamp.
493  */
494 void
495 vfs_timestamp(struct timespec *tsp)
496 {
497 	struct timeval tv;
498 
499 	switch (timestamp_precision) {
500 	case TSP_SEC:
501 		tsp->tv_sec = time_second;
502 		tsp->tv_nsec = 0;
503 		break;
504 	case TSP_HZ:
505 		getnanotime(tsp);
506 		break;
507 	case TSP_USEC:
508 		microtime(&tv);
509 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
510 		break;
511 	case TSP_NSEC:
512 	default:
513 		nanotime(tsp);
514 		break;
515 	}
516 }
517 
518 /*
519  * Set vnode attributes to VNOVAL
520  */
521 void
522 vattr_null(struct vattr *vap)
523 {
524 
525 	vap->va_type = VNON;
526 	vap->va_size = VNOVAL;
527 	vap->va_bytes = VNOVAL;
528 	vap->va_mode = VNOVAL;
529 	vap->va_nlink = VNOVAL;
530 	vap->va_uid = VNOVAL;
531 	vap->va_gid = VNOVAL;
532 	vap->va_fsid = VNOVAL;
533 	vap->va_fileid = VNOVAL;
534 	vap->va_blocksize = VNOVAL;
535 	vap->va_rdev = VNOVAL;
536 	vap->va_atime.tv_sec = VNOVAL;
537 	vap->va_atime.tv_nsec = VNOVAL;
538 	vap->va_mtime.tv_sec = VNOVAL;
539 	vap->va_mtime.tv_nsec = VNOVAL;
540 	vap->va_ctime.tv_sec = VNOVAL;
541 	vap->va_ctime.tv_nsec = VNOVAL;
542 	vap->va_birthtime.tv_sec = VNOVAL;
543 	vap->va_birthtime.tv_nsec = VNOVAL;
544 	vap->va_flags = VNOVAL;
545 	vap->va_gen = VNOVAL;
546 	vap->va_vaflags = 0;
547 }
548 
549 /*
550  * This routine is called when we have too many vnodes.  It attempts
551  * to free <count> vnodes and will potentially free vnodes that still
552  * have VM backing store (VM backing store is typically the cause
553  * of a vnode blowout so we want to do this).  Therefore, this operation
554  * is not considered cheap.
555  *
556  * A number of conditions may prevent a vnode from being reclaimed.
557  * the buffer cache may have references on the vnode, a directory
558  * vnode may still have references due to the namei cache representing
559  * underlying files, or the vnode may be in active use.   It is not
560  * desireable to reuse such vnodes.  These conditions may cause the
561  * number of vnodes to reach some minimum value regardless of what
562  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
563  */
564 static int
565 vlrureclaim(struct mount *mp)
566 {
567 	struct thread *td;
568 	struct vnode *vp;
569 	int done;
570 	int trigger;
571 	int usevnodes;
572 	int count;
573 
574 	/*
575 	 * Calculate the trigger point, don't allow user
576 	 * screwups to blow us up.   This prevents us from
577 	 * recycling vnodes with lots of resident pages.  We
578 	 * aren't trying to free memory, we are trying to
579 	 * free vnodes.
580 	 */
581 	usevnodes = desiredvnodes;
582 	if (usevnodes <= 0)
583 		usevnodes = 1;
584 	trigger = cnt.v_page_count * 2 / usevnodes;
585 	done = 0;
586 	td = curthread;
587 	vn_start_write(NULL, &mp, V_WAIT);
588 	MNT_ILOCK(mp);
589 	count = mp->mnt_nvnodelistsize / 10 + 1;
590 	while (count != 0) {
591 		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
592 		while (vp != NULL && vp->v_type == VMARKER)
593 			vp = TAILQ_NEXT(vp, v_nmntvnodes);
594 		if (vp == NULL)
595 			break;
596 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
597 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
598 		--count;
599 		if (!VI_TRYLOCK(vp))
600 			goto next_iter;
601 		/*
602 		 * If it's been deconstructed already, it's still
603 		 * referenced, or it exceeds the trigger, skip it.
604 		 */
605 		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
606 		    (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
607 		    vp->v_object->resident_page_count > trigger)) {
608 			VI_UNLOCK(vp);
609 			goto next_iter;
610 		}
611 		MNT_IUNLOCK(mp);
612 		vholdl(vp);
613 		if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT, td)) {
614 			vdrop(vp);
615 			goto next_iter_mntunlocked;
616 		}
617 		VI_LOCK(vp);
618 		/*
619 		 * v_usecount may have been bumped after VOP_LOCK() dropped
620 		 * the vnode interlock and before it was locked again.
621 		 *
622 		 * It is not necessary to recheck VI_DOOMED because it can
623 		 * only be set by another thread that holds both the vnode
624 		 * lock and vnode interlock.  If another thread has the
625 		 * vnode lock before we get to VOP_LOCK() and obtains the
626 		 * vnode interlock after VOP_LOCK() drops the vnode
627 		 * interlock, the other thread will be unable to drop the
628 		 * vnode lock before our VOP_LOCK() call fails.
629 		 */
630 		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
631 		    (vp->v_object != NULL &&
632 		    vp->v_object->resident_page_count > trigger)) {
633 			VOP_UNLOCK(vp, LK_INTERLOCK, td);
634 			goto next_iter_mntunlocked;
635 		}
636 		KASSERT((vp->v_iflag & VI_DOOMED) == 0,
637 		    ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
638 		vgonel(vp);
639 		VOP_UNLOCK(vp, 0, td);
640 		vdropl(vp);
641 		done++;
642 next_iter_mntunlocked:
643 		if ((count % 256) != 0)
644 			goto relock_mnt;
645 		goto yield;
646 next_iter:
647 		if ((count % 256) != 0)
648 			continue;
649 		MNT_IUNLOCK(mp);
650 yield:
651 		uio_yield();
652 relock_mnt:
653 		MNT_ILOCK(mp);
654 	}
655 	MNT_IUNLOCK(mp);
656 	vn_finished_write(mp);
657 	return done;
658 }
659 
660 /*
661  * Attempt to keep the free list at wantfreevnodes length.
662  */
663 static void
664 vnlru_free(int count)
665 {
666 	struct vnode *vp;
667 	int vfslocked;
668 
669 	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
670 	for (; count > 0; count--) {
671 		vp = TAILQ_FIRST(&vnode_free_list);
672 		/*
673 		 * The list can be modified while the free_list_mtx
674 		 * has been dropped and vp could be NULL here.
675 		 */
676 		if (!vp)
677 			break;
678 		VNASSERT(vp->v_op != NULL, vp,
679 		    ("vnlru_free: vnode already reclaimed."));
680 		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
681 		/*
682 		 * Don't recycle if we can't get the interlock.
683 		 */
684 		if (!VI_TRYLOCK(vp)) {
685 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
686 			continue;
687 		}
688 		VNASSERT(VCANRECYCLE(vp), vp,
689 		    ("vp inconsistent on freelist"));
690 		freevnodes--;
691 		vp->v_iflag &= ~VI_FREE;
692 		vholdl(vp);
693 		mtx_unlock(&vnode_free_list_mtx);
694 		VI_UNLOCK(vp);
695 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
696 		vtryrecycle(vp);
697 		VFS_UNLOCK_GIANT(vfslocked);
698 		/*
699 		 * If the recycled succeeded this vdrop will actually free
700 		 * the vnode.  If not it will simply place it back on
701 		 * the free list.
702 		 */
703 		vdrop(vp);
704 		mtx_lock(&vnode_free_list_mtx);
705 	}
706 }
707 /*
708  * Attempt to recycle vnodes in a context that is always safe to block.
709  * Calling vlrurecycle() from the bowels of filesystem code has some
710  * interesting deadlock problems.
711  */
712 static struct proc *vnlruproc;
713 static int vnlruproc_sig;
714 
715 static void
716 vnlru_proc(void)
717 {
718 	struct mount *mp, *nmp;
719 	int done;
720 	struct proc *p = vnlruproc;
721 	struct thread *td = FIRST_THREAD_IN_PROC(p);
722 
723 	mtx_lock(&Giant);
724 
725 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
726 	    SHUTDOWN_PRI_FIRST);
727 
728 	for (;;) {
729 		kthread_suspend_check(p);
730 		mtx_lock(&vnode_free_list_mtx);
731 		if (freevnodes > wantfreevnodes)
732 			vnlru_free(freevnodes - wantfreevnodes);
733 		if (numvnodes <= desiredvnodes * 9 / 10) {
734 			vnlruproc_sig = 0;
735 			wakeup(&vnlruproc_sig);
736 			msleep(vnlruproc, &vnode_free_list_mtx,
737 			    PVFS|PDROP, "vlruwt", hz);
738 			continue;
739 		}
740 		mtx_unlock(&vnode_free_list_mtx);
741 		done = 0;
742 		mtx_lock(&mountlist_mtx);
743 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
744 			int vfsunlocked;
745 			if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
746 				nmp = TAILQ_NEXT(mp, mnt_list);
747 				continue;
748 			}
749 			if (!VFS_NEEDSGIANT(mp)) {
750 				mtx_unlock(&Giant);
751 				vfsunlocked = 1;
752 			} else
753 				vfsunlocked = 0;
754 			done += vlrureclaim(mp);
755 			if (vfsunlocked)
756 				mtx_lock(&Giant);
757 			mtx_lock(&mountlist_mtx);
758 			nmp = TAILQ_NEXT(mp, mnt_list);
759 			vfs_unbusy(mp, td);
760 		}
761 		mtx_unlock(&mountlist_mtx);
762 		if (done == 0) {
763 			EVENTHANDLER_INVOKE(vfs_lowvnodes, desiredvnodes / 10);
764 #if 0
765 			/* These messages are temporary debugging aids */
766 			if (vnlru_nowhere < 5)
767 				printf("vnlru process getting nowhere..\n");
768 			else if (vnlru_nowhere == 5)
769 				printf("vnlru process messages stopped.\n");
770 #endif
771 			vnlru_nowhere++;
772 			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
773 		} else
774 			uio_yield();
775 	}
776 }
777 
778 static struct kproc_desc vnlru_kp = {
779 	"vnlru",
780 	vnlru_proc,
781 	&vnlruproc
782 };
783 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
784 
785 /*
786  * Routines having to do with the management of the vnode table.
787  */
788 
789 static void
790 vdestroy(struct vnode *vp)
791 {
792 	struct bufobj *bo;
793 
794 	CTR1(KTR_VFS, "vdestroy vp %p", vp);
795 	mtx_lock(&vnode_free_list_mtx);
796 	numvnodes--;
797 	mtx_unlock(&vnode_free_list_mtx);
798 	bo = &vp->v_bufobj;
799 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
800 	    ("cleaned vnode still on the free list."));
801 	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
802 	VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
803 	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
804 	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
805 	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
806 	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
807 	VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
808 	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
809 	VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
810 	VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
811 	VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
812 	VI_UNLOCK(vp);
813 #ifdef MAC
814 	mac_destroy_vnode(vp);
815 #endif
816 	if (vp->v_pollinfo != NULL) {
817 		knlist_destroy(&vp->v_pollinfo->vpi_selinfo.si_note);
818 		mtx_destroy(&vp->v_pollinfo->vpi_lock);
819 		uma_zfree(vnodepoll_zone, vp->v_pollinfo);
820 	}
821 #ifdef INVARIANTS
822 	/* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
823 	vp->v_op = NULL;
824 #endif
825 	lockdestroy(vp->v_vnlock);
826 	mtx_destroy(&vp->v_interlock);
827 	uma_zfree(vnode_zone, vp);
828 }
829 
830 /*
831  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
832  * before we actually vgone().  This function must be called with the vnode
833  * held to prevent the vnode from being returned to the free list midway
834  * through vgone().
835  */
836 static int
837 vtryrecycle(struct vnode *vp)
838 {
839 	struct thread *td = curthread;
840 	struct mount *vnmp;
841 
842 	CTR1(KTR_VFS, "vtryrecycle: trying vp %p", vp);
843 	VNASSERT(vp->v_holdcnt, vp,
844 	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
845 	/*
846 	 * This vnode may found and locked via some other list, if so we
847 	 * can't recycle it yet.
848 	 */
849 	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT, td) != 0)
850 		return (EWOULDBLOCK);
851 	/*
852 	 * Don't recycle if its filesystem is being suspended.
853 	 */
854 	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
855 		VOP_UNLOCK(vp, 0, td);
856 		return (EBUSY);
857 	}
858 	/*
859 	 * If we got this far, we need to acquire the interlock and see if
860 	 * anyone picked up this vnode from another list.  If not, we will
861 	 * mark it with DOOMED via vgonel() so that anyone who does find it
862 	 * will skip over it.
863 	 */
864 	VI_LOCK(vp);
865 	if (vp->v_usecount) {
866 		VOP_UNLOCK(vp, LK_INTERLOCK, td);
867 		vn_finished_write(vnmp);
868 		return (EBUSY);
869 	}
870 	if ((vp->v_iflag & VI_DOOMED) == 0)
871 		vgonel(vp);
872 	VOP_UNLOCK(vp, LK_INTERLOCK, td);
873 	vn_finished_write(vnmp);
874 	CTR1(KTR_VFS, "vtryrecycle: recycled vp %p", vp);
875 	return (0);
876 }
877 
878 /*
879  * Return the next vnode from the free list.
880  */
881 int
882 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
883     struct vnode **vpp)
884 {
885 	struct vnode *vp = NULL;
886 	struct bufobj *bo;
887 
888 	mtx_lock(&vnode_free_list_mtx);
889 	/*
890 	 * Lend our context to reclaim vnodes if they've exceeded the max.
891 	 */
892 	if (freevnodes > wantfreevnodes)
893 		vnlru_free(1);
894 	/*
895 	 * Wait for available vnodes.
896 	 */
897 	if (numvnodes > desiredvnodes) {
898 		if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
899 			/*
900 			 * File system is beeing suspended, we cannot risk a
901 			 * deadlock here, so allocate new vnode anyway.
902 			 */
903 			if (freevnodes > wantfreevnodes)
904 				vnlru_free(freevnodes - wantfreevnodes);
905 			goto alloc;
906 		}
907 		if (vnlruproc_sig == 0) {
908 			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
909 			wakeup(vnlruproc);
910 		}
911 		msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
912 		    "vlruwk", hz);
913 #if 0	/* XXX Not all VFS_VGET/ffs_vget callers check returns. */
914 		if (numvnodes > desiredvnodes) {
915 			mtx_unlock(&vnode_free_list_mtx);
916 			return (ENFILE);
917 		}
918 #endif
919 	}
920 alloc:
921 	numvnodes++;
922 	mtx_unlock(&vnode_free_list_mtx);
923 	vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
924 	/*
925 	 * Setup locks.
926 	 */
927 	vp->v_vnlock = &vp->v_lock;
928 	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
929 	/*
930 	 * By default, don't allow shared locks unless filesystems
931 	 * opt-in.
932 	 */
933 	lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
934 	/*
935 	 * Initialize bufobj.
936 	 */
937 	bo = &vp->v_bufobj;
938 	bo->__bo_vnode = vp;
939 	bo->bo_mtx = &vp->v_interlock;
940 	bo->bo_ops = &buf_ops_bio;
941 	bo->bo_private = vp;
942 	TAILQ_INIT(&bo->bo_clean.bv_hd);
943 	TAILQ_INIT(&bo->bo_dirty.bv_hd);
944 	/*
945 	 * Initialize namecache.
946 	 */
947 	LIST_INIT(&vp->v_cache_src);
948 	TAILQ_INIT(&vp->v_cache_dst);
949 	/*
950 	 * Finalize various vnode identity bits.
951 	 */
952 	vp->v_type = VNON;
953 	vp->v_tag = tag;
954 	vp->v_op = vops;
955 	v_incr_usecount(vp);
956 	vp->v_data = 0;
957 #ifdef MAC
958 	mac_init_vnode(vp);
959 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
960 		mac_associate_vnode_singlelabel(mp, vp);
961 	else if (mp == NULL)
962 		printf("NULL mp in getnewvnode()\n");
963 #endif
964 	if (mp != NULL) {
965 		bo->bo_bsize = mp->mnt_stat.f_iosize;
966 		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
967 			vp->v_vflag |= VV_NOKNOTE;
968 	}
969 
970 	CTR2(KTR_VFS, "getnewvnode: mp %p vp %p", mp, vp);
971 	*vpp = vp;
972 	return (0);
973 }
974 
975 /*
976  * Delete from old mount point vnode list, if on one.
977  */
978 static void
979 delmntque(struct vnode *vp)
980 {
981 	struct mount *mp;
982 
983 	mp = vp->v_mount;
984 	if (mp == NULL)
985 		return;
986 	MNT_ILOCK(mp);
987 	vp->v_mount = NULL;
988 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
989 		("bad mount point vnode list size"));
990 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
991 	mp->mnt_nvnodelistsize--;
992 	MNT_REL(mp);
993 	MNT_IUNLOCK(mp);
994 }
995 
996 static void
997 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
998 {
999 	struct thread *td;
1000 
1001 	td = curthread; /* XXX ? */
1002 	vp->v_data = NULL;
1003 	vp->v_op = &dead_vnodeops;
1004 	/* XXX non mp-safe fs may still call insmntque with vnode
1005 	   unlocked */
1006 	if (!VOP_ISLOCKED(vp, td))
1007 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1008 	vgone(vp);
1009 	vput(vp);
1010 }
1011 
1012 /*
1013  * Insert into list of vnodes for the new mount point, if available.
1014  */
1015 int
1016 insmntque1(struct vnode *vp, struct mount *mp,
1017 	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1018 {
1019 
1020 	KASSERT(vp->v_mount == NULL,
1021 		("insmntque: vnode already on per mount vnode list"));
1022 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1023 	MNT_ILOCK(mp);
1024 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1025 	    mp->mnt_nvnodelistsize == 0) {
1026 		MNT_IUNLOCK(mp);
1027 		if (dtr != NULL)
1028 			dtr(vp, dtr_arg);
1029 		return (EBUSY);
1030 	}
1031 	vp->v_mount = mp;
1032 	MNT_REF(mp);
1033 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1034 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1035 		("neg mount point vnode list size"));
1036 	mp->mnt_nvnodelistsize++;
1037 	MNT_IUNLOCK(mp);
1038 	return (0);
1039 }
1040 
1041 int
1042 insmntque(struct vnode *vp, struct mount *mp)
1043 {
1044 
1045 	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1046 }
1047 
1048 /*
1049  * Flush out and invalidate all buffers associated with a bufobj
1050  * Called with the underlying object locked.
1051  */
1052 int
1053 bufobj_invalbuf(struct bufobj *bo, int flags, struct thread *td, int slpflag,
1054     int slptimeo)
1055 {
1056 	int error;
1057 
1058 	BO_LOCK(bo);
1059 	if (flags & V_SAVE) {
1060 		error = bufobj_wwait(bo, slpflag, slptimeo);
1061 		if (error) {
1062 			BO_UNLOCK(bo);
1063 			return (error);
1064 		}
1065 		if (bo->bo_dirty.bv_cnt > 0) {
1066 			BO_UNLOCK(bo);
1067 			if ((error = BO_SYNC(bo, MNT_WAIT, td)) != 0)
1068 				return (error);
1069 			/*
1070 			 * XXX We could save a lock/unlock if this was only
1071 			 * enabled under INVARIANTS
1072 			 */
1073 			BO_LOCK(bo);
1074 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1075 				panic("vinvalbuf: dirty bufs");
1076 		}
1077 	}
1078 	/*
1079 	 * If you alter this loop please notice that interlock is dropped and
1080 	 * reacquired in flushbuflist.  Special care is needed to ensure that
1081 	 * no race conditions occur from this.
1082 	 */
1083 	do {
1084 		error = flushbuflist(&bo->bo_clean,
1085 		    flags, bo, slpflag, slptimeo);
1086 		if (error == 0)
1087 			error = flushbuflist(&bo->bo_dirty,
1088 			    flags, bo, slpflag, slptimeo);
1089 		if (error != 0 && error != EAGAIN) {
1090 			BO_UNLOCK(bo);
1091 			return (error);
1092 		}
1093 	} while (error != 0);
1094 
1095 	/*
1096 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1097 	 * have write I/O in-progress but if there is a VM object then the
1098 	 * VM object can also have read-I/O in-progress.
1099 	 */
1100 	do {
1101 		bufobj_wwait(bo, 0, 0);
1102 		BO_UNLOCK(bo);
1103 		if (bo->bo_object != NULL) {
1104 			VM_OBJECT_LOCK(bo->bo_object);
1105 			vm_object_pip_wait(bo->bo_object, "bovlbx");
1106 			VM_OBJECT_UNLOCK(bo->bo_object);
1107 		}
1108 		BO_LOCK(bo);
1109 	} while (bo->bo_numoutput > 0);
1110 	BO_UNLOCK(bo);
1111 
1112 	/*
1113 	 * Destroy the copy in the VM cache, too.
1114 	 */
1115 	if (bo->bo_object != NULL) {
1116 		VM_OBJECT_LOCK(bo->bo_object);
1117 		vm_object_page_remove(bo->bo_object, 0, 0,
1118 			(flags & V_SAVE) ? TRUE : FALSE);
1119 		VM_OBJECT_UNLOCK(bo->bo_object);
1120 	}
1121 
1122 #ifdef INVARIANTS
1123 	BO_LOCK(bo);
1124 	if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1125 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1126 		panic("vinvalbuf: flush failed");
1127 	BO_UNLOCK(bo);
1128 #endif
1129 	return (0);
1130 }
1131 
1132 /*
1133  * Flush out and invalidate all buffers associated with a vnode.
1134  * Called with the underlying object locked.
1135  */
1136 int
1137 vinvalbuf(struct vnode *vp, int flags, struct thread *td, int slpflag,
1138     int slptimeo)
1139 {
1140 
1141 	CTR2(KTR_VFS, "vinvalbuf vp %p flags %d", vp, flags);
1142 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1143 	return (bufobj_invalbuf(&vp->v_bufobj, flags, td, slpflag, slptimeo));
1144 }
1145 
1146 /*
1147  * Flush out buffers on the specified list.
1148  *
1149  */
1150 static int
1151 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1152     int slptimeo)
1153 {
1154 	struct buf *bp, *nbp;
1155 	int retval, error;
1156 	daddr_t lblkno;
1157 	b_xflags_t xflags;
1158 
1159 	ASSERT_BO_LOCKED(bo);
1160 
1161 	retval = 0;
1162 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1163 		if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1164 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1165 			continue;
1166 		}
1167 		lblkno = 0;
1168 		xflags = 0;
1169 		if (nbp != NULL) {
1170 			lblkno = nbp->b_lblkno;
1171 			xflags = nbp->b_xflags &
1172 				(BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1173 		}
1174 		retval = EAGAIN;
1175 		error = BUF_TIMELOCK(bp,
1176 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1177 		    "flushbuf", slpflag, slptimeo);
1178 		if (error) {
1179 			BO_LOCK(bo);
1180 			return (error != ENOLCK ? error : EAGAIN);
1181 		}
1182 		KASSERT(bp->b_bufobj == bo,
1183 		    ("bp %p wrong b_bufobj %p should be %p",
1184 		    bp, bp->b_bufobj, bo));
1185 		if (bp->b_bufobj != bo) {	/* XXX: necessary ? */
1186 			BUF_UNLOCK(bp);
1187 			BO_LOCK(bo);
1188 			return (EAGAIN);
1189 		}
1190 		/*
1191 		 * XXX Since there are no node locks for NFS, I
1192 		 * believe there is a slight chance that a delayed
1193 		 * write will occur while sleeping just above, so
1194 		 * check for it.
1195 		 */
1196 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1197 		    (flags & V_SAVE)) {
1198 			bremfree(bp);
1199 			bp->b_flags |= B_ASYNC;
1200 			bwrite(bp);
1201 			BO_LOCK(bo);
1202 			return (EAGAIN);	/* XXX: why not loop ? */
1203 		}
1204 		bremfree(bp);
1205 		bp->b_flags |= (B_INVAL | B_RELBUF);
1206 		bp->b_flags &= ~B_ASYNC;
1207 		brelse(bp);
1208 		BO_LOCK(bo);
1209 		if (nbp != NULL &&
1210 		    (nbp->b_bufobj != bo ||
1211 		     nbp->b_lblkno != lblkno ||
1212 		     (nbp->b_xflags &
1213 		      (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1214 			break;			/* nbp invalid */
1215 	}
1216 	return (retval);
1217 }
1218 
1219 /*
1220  * Truncate a file's buffer and pages to a specified length.  This
1221  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1222  * sync activity.
1223  */
1224 int
1225 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1226     off_t length, int blksize)
1227 {
1228 	struct buf *bp, *nbp;
1229 	int anyfreed;
1230 	int trunclbn;
1231 	struct bufobj *bo;
1232 
1233 	CTR2(KTR_VFS, "vtruncbuf vp %p length %jd", vp, length);
1234 	/*
1235 	 * Round up to the *next* lbn.
1236 	 */
1237 	trunclbn = (length + blksize - 1) / blksize;
1238 
1239 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1240 restart:
1241 	VI_LOCK(vp);
1242 	bo = &vp->v_bufobj;
1243 	anyfreed = 1;
1244 	for (;anyfreed;) {
1245 		anyfreed = 0;
1246 		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1247 			if (bp->b_lblkno < trunclbn)
1248 				continue;
1249 			if (BUF_LOCK(bp,
1250 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1251 			    VI_MTX(vp)) == ENOLCK)
1252 				goto restart;
1253 
1254 			bremfree(bp);
1255 			bp->b_flags |= (B_INVAL | B_RELBUF);
1256 			bp->b_flags &= ~B_ASYNC;
1257 			brelse(bp);
1258 			anyfreed = 1;
1259 
1260 			if (nbp != NULL &&
1261 			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1262 			    (nbp->b_vp != vp) ||
1263 			    (nbp->b_flags & B_DELWRI))) {
1264 				goto restart;
1265 			}
1266 			VI_LOCK(vp);
1267 		}
1268 
1269 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1270 			if (bp->b_lblkno < trunclbn)
1271 				continue;
1272 			if (BUF_LOCK(bp,
1273 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1274 			    VI_MTX(vp)) == ENOLCK)
1275 				goto restart;
1276 			bremfree(bp);
1277 			bp->b_flags |= (B_INVAL | B_RELBUF);
1278 			bp->b_flags &= ~B_ASYNC;
1279 			brelse(bp);
1280 			anyfreed = 1;
1281 			if (nbp != NULL &&
1282 			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1283 			    (nbp->b_vp != vp) ||
1284 			    (nbp->b_flags & B_DELWRI) == 0)) {
1285 				goto restart;
1286 			}
1287 			VI_LOCK(vp);
1288 		}
1289 	}
1290 
1291 	if (length > 0) {
1292 restartsync:
1293 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1294 			if (bp->b_lblkno > 0)
1295 				continue;
1296 			/*
1297 			 * Since we hold the vnode lock this should only
1298 			 * fail if we're racing with the buf daemon.
1299 			 */
1300 			if (BUF_LOCK(bp,
1301 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1302 			    VI_MTX(vp)) == ENOLCK) {
1303 				goto restart;
1304 			}
1305 			VNASSERT((bp->b_flags & B_DELWRI), vp,
1306 			    ("buf(%p) on dirty queue without DELWRI", bp));
1307 
1308 			bremfree(bp);
1309 			bawrite(bp);
1310 			VI_LOCK(vp);
1311 			goto restartsync;
1312 		}
1313 	}
1314 
1315 	bufobj_wwait(bo, 0, 0);
1316 	VI_UNLOCK(vp);
1317 	vnode_pager_setsize(vp, length);
1318 
1319 	return (0);
1320 }
1321 
1322 /*
1323  * buf_splay() - splay tree core for the clean/dirty list of buffers in
1324  * 		 a vnode.
1325  *
1326  *	NOTE: We have to deal with the special case of a background bitmap
1327  *	buffer, a situation where two buffers will have the same logical
1328  *	block offset.  We want (1) only the foreground buffer to be accessed
1329  *	in a lookup and (2) must differentiate between the foreground and
1330  *	background buffer in the splay tree algorithm because the splay
1331  *	tree cannot normally handle multiple entities with the same 'index'.
1332  *	We accomplish this by adding differentiating flags to the splay tree's
1333  *	numerical domain.
1334  */
1335 static
1336 struct buf *
1337 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1338 {
1339 	struct buf dummy;
1340 	struct buf *lefttreemax, *righttreemin, *y;
1341 
1342 	if (root == NULL)
1343 		return (NULL);
1344 	lefttreemax = righttreemin = &dummy;
1345 	for (;;) {
1346 		if (lblkno < root->b_lblkno ||
1347 		    (lblkno == root->b_lblkno &&
1348 		    (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1349 			if ((y = root->b_left) == NULL)
1350 				break;
1351 			if (lblkno < y->b_lblkno) {
1352 				/* Rotate right. */
1353 				root->b_left = y->b_right;
1354 				y->b_right = root;
1355 				root = y;
1356 				if ((y = root->b_left) == NULL)
1357 					break;
1358 			}
1359 			/* Link into the new root's right tree. */
1360 			righttreemin->b_left = root;
1361 			righttreemin = root;
1362 		} else if (lblkno > root->b_lblkno ||
1363 		    (lblkno == root->b_lblkno &&
1364 		    (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1365 			if ((y = root->b_right) == NULL)
1366 				break;
1367 			if (lblkno > y->b_lblkno) {
1368 				/* Rotate left. */
1369 				root->b_right = y->b_left;
1370 				y->b_left = root;
1371 				root = y;
1372 				if ((y = root->b_right) == NULL)
1373 					break;
1374 			}
1375 			/* Link into the new root's left tree. */
1376 			lefttreemax->b_right = root;
1377 			lefttreemax = root;
1378 		} else {
1379 			break;
1380 		}
1381 		root = y;
1382 	}
1383 	/* Assemble the new root. */
1384 	lefttreemax->b_right = root->b_left;
1385 	righttreemin->b_left = root->b_right;
1386 	root->b_left = dummy.b_right;
1387 	root->b_right = dummy.b_left;
1388 	return (root);
1389 }
1390 
1391 static void
1392 buf_vlist_remove(struct buf *bp)
1393 {
1394 	struct buf *root;
1395 	struct bufv *bv;
1396 
1397 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1398 	ASSERT_BO_LOCKED(bp->b_bufobj);
1399 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1400 	    (BX_VNDIRTY|BX_VNCLEAN),
1401 	    ("buf_vlist_remove: Buf %p is on two lists", bp));
1402 	if (bp->b_xflags & BX_VNDIRTY)
1403 		bv = &bp->b_bufobj->bo_dirty;
1404 	else
1405 		bv = &bp->b_bufobj->bo_clean;
1406 	if (bp != bv->bv_root) {
1407 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1408 		KASSERT(root == bp, ("splay lookup failed in remove"));
1409 	}
1410 	if (bp->b_left == NULL) {
1411 		root = bp->b_right;
1412 	} else {
1413 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1414 		root->b_right = bp->b_right;
1415 	}
1416 	bv->bv_root = root;
1417 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1418 	bv->bv_cnt--;
1419 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1420 }
1421 
1422 /*
1423  * Add the buffer to the sorted clean or dirty block list using a
1424  * splay tree algorithm.
1425  *
1426  * NOTE: xflags is passed as a constant, optimizing this inline function!
1427  */
1428 static void
1429 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1430 {
1431 	struct buf *root;
1432 	struct bufv *bv;
1433 
1434 	ASSERT_BO_LOCKED(bo);
1435 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1436 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1437 	bp->b_xflags |= xflags;
1438 	if (xflags & BX_VNDIRTY)
1439 		bv = &bo->bo_dirty;
1440 	else
1441 		bv = &bo->bo_clean;
1442 
1443 	root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1444 	if (root == NULL) {
1445 		bp->b_left = NULL;
1446 		bp->b_right = NULL;
1447 		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1448 	} else if (bp->b_lblkno < root->b_lblkno ||
1449 	    (bp->b_lblkno == root->b_lblkno &&
1450 	    (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1451 		bp->b_left = root->b_left;
1452 		bp->b_right = root;
1453 		root->b_left = NULL;
1454 		TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1455 	} else {
1456 		bp->b_right = root->b_right;
1457 		bp->b_left = root;
1458 		root->b_right = NULL;
1459 		TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1460 	}
1461 	bv->bv_cnt++;
1462 	bv->bv_root = bp;
1463 }
1464 
1465 /*
1466  * Lookup a buffer using the splay tree.  Note that we specifically avoid
1467  * shadow buffers used in background bitmap writes.
1468  *
1469  * This code isn't quite efficient as it could be because we are maintaining
1470  * two sorted lists and do not know which list the block resides in.
1471  *
1472  * During a "make buildworld" the desired buffer is found at one of
1473  * the roots more than 60% of the time.  Thus, checking both roots
1474  * before performing either splay eliminates unnecessary splays on the
1475  * first tree splayed.
1476  */
1477 struct buf *
1478 gbincore(struct bufobj *bo, daddr_t lblkno)
1479 {
1480 	struct buf *bp;
1481 
1482 	ASSERT_BO_LOCKED(bo);
1483 	if ((bp = bo->bo_clean.bv_root) != NULL &&
1484 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1485 		return (bp);
1486 	if ((bp = bo->bo_dirty.bv_root) != NULL &&
1487 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1488 		return (bp);
1489 	if ((bp = bo->bo_clean.bv_root) != NULL) {
1490 		bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1491 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1492 			return (bp);
1493 	}
1494 	if ((bp = bo->bo_dirty.bv_root) != NULL) {
1495 		bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1496 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1497 			return (bp);
1498 	}
1499 	return (NULL);
1500 }
1501 
1502 /*
1503  * Associate a buffer with a vnode.
1504  */
1505 void
1506 bgetvp(struct vnode *vp, struct buf *bp)
1507 {
1508 
1509 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1510 
1511 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1512 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1513 	    ("bgetvp: bp already attached! %p", bp));
1514 
1515 	ASSERT_VI_LOCKED(vp, "bgetvp");
1516 	vholdl(vp);
1517 	if (VFS_NEEDSGIANT(vp->v_mount) ||
1518 	    vp->v_bufobj.bo_flag & BO_NEEDSGIANT)
1519 		bp->b_flags |= B_NEEDSGIANT;
1520 	bp->b_vp = vp;
1521 	bp->b_bufobj = &vp->v_bufobj;
1522 	/*
1523 	 * Insert onto list for new vnode.
1524 	 */
1525 	buf_vlist_add(bp, &vp->v_bufobj, BX_VNCLEAN);
1526 }
1527 
1528 /*
1529  * Disassociate a buffer from a vnode.
1530  */
1531 void
1532 brelvp(struct buf *bp)
1533 {
1534 	struct bufobj *bo;
1535 	struct vnode *vp;
1536 
1537 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1538 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1539 
1540 	/*
1541 	 * Delete from old vnode list, if on one.
1542 	 */
1543 	vp = bp->b_vp;		/* XXX */
1544 	bo = bp->b_bufobj;
1545 	BO_LOCK(bo);
1546 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1547 		buf_vlist_remove(bp);
1548 	else
1549 		panic("brelvp: Buffer %p not on queue.", bp);
1550 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1551 		bo->bo_flag &= ~BO_ONWORKLST;
1552 		mtx_lock(&sync_mtx);
1553 		LIST_REMOVE(bo, bo_synclist);
1554 		syncer_worklist_len--;
1555 		mtx_unlock(&sync_mtx);
1556 	}
1557 	bp->b_flags &= ~B_NEEDSGIANT;
1558 	bp->b_vp = NULL;
1559 	bp->b_bufobj = NULL;
1560 	vdropl(vp);
1561 }
1562 
1563 /*
1564  * Add an item to the syncer work queue.
1565  */
1566 static void
1567 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1568 {
1569 	int slot;
1570 
1571 	ASSERT_BO_LOCKED(bo);
1572 
1573 	mtx_lock(&sync_mtx);
1574 	if (bo->bo_flag & BO_ONWORKLST)
1575 		LIST_REMOVE(bo, bo_synclist);
1576 	else {
1577 		bo->bo_flag |= BO_ONWORKLST;
1578 		syncer_worklist_len++;
1579 	}
1580 
1581 	if (delay > syncer_maxdelay - 2)
1582 		delay = syncer_maxdelay - 2;
1583 	slot = (syncer_delayno + delay) & syncer_mask;
1584 
1585 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
1586 	mtx_unlock(&sync_mtx);
1587 }
1588 
1589 static int
1590 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1591 {
1592 	int error, len;
1593 
1594 	mtx_lock(&sync_mtx);
1595 	len = syncer_worklist_len - sync_vnode_count;
1596 	mtx_unlock(&sync_mtx);
1597 	error = SYSCTL_OUT(req, &len, sizeof(len));
1598 	return (error);
1599 }
1600 
1601 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1602     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1603 
1604 static struct proc *updateproc;
1605 static void sched_sync(void);
1606 static struct kproc_desc up_kp = {
1607 	"syncer",
1608 	sched_sync,
1609 	&updateproc
1610 };
1611 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1612 
1613 static int
1614 sync_vnode(struct bufobj *bo, struct thread *td)
1615 {
1616 	struct vnode *vp;
1617 	struct mount *mp;
1618 
1619 	vp = bo->__bo_vnode;	/* XXX */
1620 	if (VOP_ISLOCKED(vp, NULL) != 0)
1621 		return (1);
1622 	if (VI_TRYLOCK(vp) == 0)
1623 		return (1);
1624 	/*
1625 	 * We use vhold in case the vnode does not
1626 	 * successfully sync.  vhold prevents the vnode from
1627 	 * going away when we unlock the sync_mtx so that
1628 	 * we can acquire the vnode interlock.
1629 	 */
1630 	vholdl(vp);
1631 	mtx_unlock(&sync_mtx);
1632 	VI_UNLOCK(vp);
1633 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1634 		vdrop(vp);
1635 		mtx_lock(&sync_mtx);
1636 		return (1);
1637 	}
1638 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1639 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
1640 	VOP_UNLOCK(vp, 0, td);
1641 	vn_finished_write(mp);
1642 	VI_LOCK(vp);
1643 	if ((bo->bo_flag & BO_ONWORKLST) != 0) {
1644 		/*
1645 		 * Put us back on the worklist.  The worklist
1646 		 * routine will remove us from our current
1647 		 * position and then add us back in at a later
1648 		 * position.
1649 		 */
1650 		vn_syncer_add_to_worklist(bo, syncdelay);
1651 	}
1652 	vdropl(vp);
1653 	mtx_lock(&sync_mtx);
1654 	return (0);
1655 }
1656 
1657 /*
1658  * System filesystem synchronizer daemon.
1659  */
1660 static void
1661 sched_sync(void)
1662 {
1663 	struct synclist *next;
1664 	struct synclist *slp;
1665 	struct bufobj *bo;
1666 	long starttime;
1667 	struct thread *td = FIRST_THREAD_IN_PROC(updateproc);
1668 	static int dummychan;
1669 	int last_work_seen;
1670 	int net_worklist_len;
1671 	int syncer_final_iter;
1672 	int first_printf;
1673 	int error;
1674 
1675 	mtx_lock(&Giant);
1676 	last_work_seen = 0;
1677 	syncer_final_iter = 0;
1678 	first_printf = 1;
1679 	syncer_state = SYNCER_RUNNING;
1680 	starttime = time_uptime;
1681 	td->td_pflags |= TDP_NORUNNINGBUF;
1682 
1683 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1684 	    SHUTDOWN_PRI_LAST);
1685 
1686 	mtx_lock(&sync_mtx);
1687 	for (;;) {
1688 		if (syncer_state == SYNCER_FINAL_DELAY &&
1689 		    syncer_final_iter == 0) {
1690 			mtx_unlock(&sync_mtx);
1691 			kthread_suspend_check(td->td_proc);
1692 			mtx_lock(&sync_mtx);
1693 		}
1694 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
1695 		if (syncer_state != SYNCER_RUNNING &&
1696 		    starttime != time_uptime) {
1697 			if (first_printf) {
1698 				printf("\nSyncing disks, vnodes remaining...");
1699 				first_printf = 0;
1700 			}
1701 			printf("%d ", net_worklist_len);
1702 		}
1703 		starttime = time_uptime;
1704 
1705 		/*
1706 		 * Push files whose dirty time has expired.  Be careful
1707 		 * of interrupt race on slp queue.
1708 		 *
1709 		 * Skip over empty worklist slots when shutting down.
1710 		 */
1711 		do {
1712 			slp = &syncer_workitem_pending[syncer_delayno];
1713 			syncer_delayno += 1;
1714 			if (syncer_delayno == syncer_maxdelay)
1715 				syncer_delayno = 0;
1716 			next = &syncer_workitem_pending[syncer_delayno];
1717 			/*
1718 			 * If the worklist has wrapped since the
1719 			 * it was emptied of all but syncer vnodes,
1720 			 * switch to the FINAL_DELAY state and run
1721 			 * for one more second.
1722 			 */
1723 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
1724 			    net_worklist_len == 0 &&
1725 			    last_work_seen == syncer_delayno) {
1726 				syncer_state = SYNCER_FINAL_DELAY;
1727 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1728 			}
1729 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1730 		    syncer_worklist_len > 0);
1731 
1732 		/*
1733 		 * Keep track of the last time there was anything
1734 		 * on the worklist other than syncer vnodes.
1735 		 * Return to the SHUTTING_DOWN state if any
1736 		 * new work appears.
1737 		 */
1738 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1739 			last_work_seen = syncer_delayno;
1740 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1741 			syncer_state = SYNCER_SHUTTING_DOWN;
1742 		while ((bo = LIST_FIRST(slp)) != NULL) {
1743 			error = sync_vnode(bo, td);
1744 			if (error == 1) {
1745 				LIST_REMOVE(bo, bo_synclist);
1746 				LIST_INSERT_HEAD(next, bo, bo_synclist);
1747 				continue;
1748 			}
1749 		}
1750 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1751 			syncer_final_iter--;
1752 		/*
1753 		 * The variable rushjob allows the kernel to speed up the
1754 		 * processing of the filesystem syncer process. A rushjob
1755 		 * value of N tells the filesystem syncer to process the next
1756 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1757 		 * is used by the soft update code to speed up the filesystem
1758 		 * syncer process when the incore state is getting so far
1759 		 * ahead of the disk that the kernel memory pool is being
1760 		 * threatened with exhaustion.
1761 		 */
1762 		if (rushjob > 0) {
1763 			rushjob -= 1;
1764 			continue;
1765 		}
1766 		/*
1767 		 * Just sleep for a short period of time between
1768 		 * iterations when shutting down to allow some I/O
1769 		 * to happen.
1770 		 *
1771 		 * If it has taken us less than a second to process the
1772 		 * current work, then wait. Otherwise start right over
1773 		 * again. We can still lose time if any single round
1774 		 * takes more than two seconds, but it does not really
1775 		 * matter as we are just trying to generally pace the
1776 		 * filesystem activity.
1777 		 */
1778 		if (syncer_state != SYNCER_RUNNING)
1779 			msleep(&dummychan, &sync_mtx, PPAUSE, "syncfnl",
1780 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
1781 		else if (time_uptime == starttime)
1782 			msleep(&lbolt, &sync_mtx, PPAUSE, "syncer", 0);
1783 	}
1784 }
1785 
1786 /*
1787  * Request the syncer daemon to speed up its work.
1788  * We never push it to speed up more than half of its
1789  * normal turn time, otherwise it could take over the cpu.
1790  */
1791 int
1792 speedup_syncer(void)
1793 {
1794 	struct thread *td;
1795 	int ret = 0;
1796 
1797 	td = FIRST_THREAD_IN_PROC(updateproc);
1798 	sleepq_remove(td, &lbolt);
1799 	mtx_lock(&sync_mtx);
1800 	if (rushjob < syncdelay / 2) {
1801 		rushjob += 1;
1802 		stat_rush_requests += 1;
1803 		ret = 1;
1804 	}
1805 	mtx_unlock(&sync_mtx);
1806 	return (ret);
1807 }
1808 
1809 /*
1810  * Tell the syncer to speed up its work and run though its work
1811  * list several times, then tell it to shut down.
1812  */
1813 static void
1814 syncer_shutdown(void *arg, int howto)
1815 {
1816 	struct thread *td;
1817 
1818 	if (howto & RB_NOSYNC)
1819 		return;
1820 	td = FIRST_THREAD_IN_PROC(updateproc);
1821 	sleepq_remove(td, &lbolt);
1822 	mtx_lock(&sync_mtx);
1823 	syncer_state = SYNCER_SHUTTING_DOWN;
1824 	rushjob = 0;
1825 	mtx_unlock(&sync_mtx);
1826 	kproc_shutdown(arg, howto);
1827 }
1828 
1829 /*
1830  * Reassign a buffer from one vnode to another.
1831  * Used to assign file specific control information
1832  * (indirect blocks) to the vnode to which they belong.
1833  */
1834 void
1835 reassignbuf(struct buf *bp)
1836 {
1837 	struct vnode *vp;
1838 	struct bufobj *bo;
1839 	int delay;
1840 #ifdef INVARIANTS
1841 	struct bufv *bv;
1842 #endif
1843 
1844 	vp = bp->b_vp;
1845 	bo = bp->b_bufobj;
1846 	++reassignbufcalls;
1847 
1848 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1849 	    bp, bp->b_vp, bp->b_flags);
1850 	/*
1851 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1852 	 * is not fully linked in.
1853 	 */
1854 	if (bp->b_flags & B_PAGING)
1855 		panic("cannot reassign paging buffer");
1856 
1857 	/*
1858 	 * Delete from old vnode list, if on one.
1859 	 */
1860 	VI_LOCK(vp);
1861 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1862 		buf_vlist_remove(bp);
1863 	else
1864 		panic("reassignbuf: Buffer %p not on queue.", bp);
1865 	/*
1866 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1867 	 * of clean buffers.
1868 	 */
1869 	if (bp->b_flags & B_DELWRI) {
1870 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1871 			switch (vp->v_type) {
1872 			case VDIR:
1873 				delay = dirdelay;
1874 				break;
1875 			case VCHR:
1876 				delay = metadelay;
1877 				break;
1878 			default:
1879 				delay = filedelay;
1880 			}
1881 			vn_syncer_add_to_worklist(bo, delay);
1882 		}
1883 		buf_vlist_add(bp, bo, BX_VNDIRTY);
1884 	} else {
1885 		buf_vlist_add(bp, bo, BX_VNCLEAN);
1886 
1887 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1888 			mtx_lock(&sync_mtx);
1889 			LIST_REMOVE(bo, bo_synclist);
1890 			syncer_worklist_len--;
1891 			mtx_unlock(&sync_mtx);
1892 			bo->bo_flag &= ~BO_ONWORKLST;
1893 		}
1894 	}
1895 #ifdef INVARIANTS
1896 	bv = &bo->bo_clean;
1897 	bp = TAILQ_FIRST(&bv->bv_hd);
1898 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1899 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1900 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1901 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1902 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1903 	bv = &bo->bo_dirty;
1904 	bp = TAILQ_FIRST(&bv->bv_hd);
1905 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1906 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1907 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1908 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1909 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1910 #endif
1911 	VI_UNLOCK(vp);
1912 }
1913 
1914 /*
1915  * Increment the use and hold counts on the vnode, taking care to reference
1916  * the driver's usecount if this is a chardev.  The vholdl() will remove
1917  * the vnode from the free list if it is presently free.  Requires the
1918  * vnode interlock and returns with it held.
1919  */
1920 static void
1921 v_incr_usecount(struct vnode *vp)
1922 {
1923 
1924 	CTR3(KTR_VFS, "v_incr_usecount: vp %p holdcnt %d usecount %d\n",
1925 	    vp, vp->v_holdcnt, vp->v_usecount);
1926 	vp->v_usecount++;
1927 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1928 		dev_lock();
1929 		vp->v_rdev->si_usecount++;
1930 		dev_unlock();
1931 	}
1932 	vholdl(vp);
1933 }
1934 
1935 /*
1936  * Turn a holdcnt into a use+holdcnt such that only one call to
1937  * v_decr_usecount is needed.
1938  */
1939 static void
1940 v_upgrade_usecount(struct vnode *vp)
1941 {
1942 
1943 	CTR3(KTR_VFS, "v_upgrade_usecount: vp %p holdcnt %d usecount %d\n",
1944 	    vp, vp->v_holdcnt, vp->v_usecount);
1945 	vp->v_usecount++;
1946 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1947 		dev_lock();
1948 		vp->v_rdev->si_usecount++;
1949 		dev_unlock();
1950 	}
1951 }
1952 
1953 /*
1954  * Decrement the vnode use and hold count along with the driver's usecount
1955  * if this is a chardev.  The vdropl() below releases the vnode interlock
1956  * as it may free the vnode.
1957  */
1958 static void
1959 v_decr_usecount(struct vnode *vp)
1960 {
1961 
1962 	CTR3(KTR_VFS, "v_decr_usecount: vp %p holdcnt %d usecount %d\n",
1963 	    vp, vp->v_holdcnt, vp->v_usecount);
1964 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
1965 	VNASSERT(vp->v_usecount > 0, vp,
1966 	    ("v_decr_usecount: negative usecount"));
1967 	vp->v_usecount--;
1968 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1969 		dev_lock();
1970 		vp->v_rdev->si_usecount--;
1971 		dev_unlock();
1972 	}
1973 	vdropl(vp);
1974 }
1975 
1976 /*
1977  * Decrement only the use count and driver use count.  This is intended to
1978  * be paired with a follow on vdropl() to release the remaining hold count.
1979  * In this way we may vgone() a vnode with a 0 usecount without risk of
1980  * having it end up on a free list because the hold count is kept above 0.
1981  */
1982 static void
1983 v_decr_useonly(struct vnode *vp)
1984 {
1985 
1986 	CTR3(KTR_VFS, "v_decr_useonly: vp %p holdcnt %d usecount %d\n",
1987 	    vp, vp->v_holdcnt, vp->v_usecount);
1988 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
1989 	VNASSERT(vp->v_usecount > 0, vp,
1990 	    ("v_decr_useonly: negative usecount"));
1991 	vp->v_usecount--;
1992 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1993 		dev_lock();
1994 		vp->v_rdev->si_usecount--;
1995 		dev_unlock();
1996 	}
1997 }
1998 
1999 /*
2000  * Grab a particular vnode from the free list, increment its
2001  * reference count and lock it. The vnode lock bit is set if the
2002  * vnode is being eliminated in vgone. The process is awakened
2003  * when the transition is completed, and an error returned to
2004  * indicate that the vnode is no longer usable (possibly having
2005  * been changed to a new filesystem type).
2006  */
2007 int
2008 vget(struct vnode *vp, int flags, struct thread *td)
2009 {
2010 	int oweinact;
2011 	int oldflags;
2012 	int error;
2013 
2014 	error = 0;
2015 	oldflags = flags;
2016 	oweinact = 0;
2017 	VFS_ASSERT_GIANT(vp->v_mount);
2018 	if ((flags & LK_INTERLOCK) == 0)
2019 		VI_LOCK(vp);
2020 	/*
2021 	 * If the inactive call was deferred because vput() was called
2022 	 * with a shared lock, we have to do it here before another thread
2023 	 * gets a reference to data that should be dead.
2024 	 */
2025 	if (vp->v_iflag & VI_OWEINACT) {
2026 		if (flags & LK_NOWAIT) {
2027 			VI_UNLOCK(vp);
2028 			return (EBUSY);
2029 		}
2030 		flags &= ~LK_TYPE_MASK;
2031 		flags |= LK_EXCLUSIVE;
2032 		oweinact = 1;
2033 	}
2034 	vholdl(vp);
2035 	if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
2036 		vdrop(vp);
2037 		return (error);
2038 	}
2039 	VI_LOCK(vp);
2040 	/* Upgrade our holdcnt to a usecount. */
2041 	v_upgrade_usecount(vp);
2042 	if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2043 		panic("vget: vn_lock failed to return ENOENT\n");
2044 	if (oweinact) {
2045 		if (vp->v_iflag & VI_OWEINACT)
2046 			vinactive(vp, td);
2047 		VI_UNLOCK(vp);
2048 		if ((oldflags & LK_TYPE_MASK) == 0)
2049 			VOP_UNLOCK(vp, 0, td);
2050 	} else
2051 		VI_UNLOCK(vp);
2052 	return (0);
2053 }
2054 
2055 /*
2056  * Increase the reference count of a vnode.
2057  */
2058 void
2059 vref(struct vnode *vp)
2060 {
2061 
2062 	VI_LOCK(vp);
2063 	v_incr_usecount(vp);
2064 	VI_UNLOCK(vp);
2065 }
2066 
2067 /*
2068  * Return reference count of a vnode.
2069  *
2070  * The results of this call are only guaranteed when some mechanism other
2071  * than the VI lock is used to stop other processes from gaining references
2072  * to the vnode.  This may be the case if the caller holds the only reference.
2073  * This is also useful when stale data is acceptable as race conditions may
2074  * be accounted for by some other means.
2075  */
2076 int
2077 vrefcnt(struct vnode *vp)
2078 {
2079 	int usecnt;
2080 
2081 	VI_LOCK(vp);
2082 	usecnt = vp->v_usecount;
2083 	VI_UNLOCK(vp);
2084 
2085 	return (usecnt);
2086 }
2087 
2088 
2089 /*
2090  * Vnode put/release.
2091  * If count drops to zero, call inactive routine and return to freelist.
2092  */
2093 void
2094 vrele(struct vnode *vp)
2095 {
2096 	struct thread *td = curthread;	/* XXX */
2097 
2098 	KASSERT(vp != NULL, ("vrele: null vp"));
2099 	VFS_ASSERT_GIANT(vp->v_mount);
2100 
2101 	VI_LOCK(vp);
2102 
2103 	/* Skip this v_writecount check if we're going to panic below. */
2104 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2105 	    ("vrele: missed vn_close"));
2106 
2107 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2108 	    vp->v_usecount == 1)) {
2109 		v_decr_usecount(vp);
2110 		return;
2111 	}
2112 	if (vp->v_usecount != 1) {
2113 #ifdef DIAGNOSTIC
2114 		vprint("vrele: negative ref count", vp);
2115 #endif
2116 		VI_UNLOCK(vp);
2117 		panic("vrele: negative ref cnt");
2118 	}
2119 	/*
2120 	 * We want to hold the vnode until the inactive finishes to
2121 	 * prevent vgone() races.  We drop the use count here and the
2122 	 * hold count below when we're done.
2123 	 */
2124 	v_decr_useonly(vp);
2125 	/*
2126 	 * We must call VOP_INACTIVE with the node locked. Mark
2127 	 * as VI_DOINGINACT to avoid recursion.
2128 	 */
2129 	vp->v_iflag |= VI_OWEINACT;
2130 	if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0) {
2131 		VI_LOCK(vp);
2132 		if (vp->v_usecount > 0)
2133 			vp->v_iflag &= ~VI_OWEINACT;
2134 		if (vp->v_iflag & VI_OWEINACT)
2135 			vinactive(vp, td);
2136 		VOP_UNLOCK(vp, 0, td);
2137 	} else {
2138 		VI_LOCK(vp);
2139 		if (vp->v_usecount > 0)
2140 			vp->v_iflag &= ~VI_OWEINACT;
2141 	}
2142 	vdropl(vp);
2143 }
2144 
2145 /*
2146  * Release an already locked vnode.  This give the same effects as
2147  * unlock+vrele(), but takes less time and avoids releasing and
2148  * re-aquiring the lock (as vrele() acquires the lock internally.)
2149  */
2150 void
2151 vput(struct vnode *vp)
2152 {
2153 	struct thread *td = curthread;	/* XXX */
2154 	int error;
2155 
2156 	KASSERT(vp != NULL, ("vput: null vp"));
2157 	ASSERT_VOP_LOCKED(vp, "vput");
2158 	VFS_ASSERT_GIANT(vp->v_mount);
2159 	VI_LOCK(vp);
2160 	/* Skip this v_writecount check if we're going to panic below. */
2161 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2162 	    ("vput: missed vn_close"));
2163 	error = 0;
2164 
2165 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2166 	    vp->v_usecount == 1)) {
2167 		VOP_UNLOCK(vp, 0, td);
2168 		v_decr_usecount(vp);
2169 		return;
2170 	}
2171 
2172 	if (vp->v_usecount != 1) {
2173 #ifdef DIAGNOSTIC
2174 		vprint("vput: negative ref count", vp);
2175 #endif
2176 		panic("vput: negative ref cnt");
2177 	}
2178 	/*
2179 	 * We want to hold the vnode until the inactive finishes to
2180 	 * prevent vgone() races.  We drop the use count here and the
2181 	 * hold count below when we're done.
2182 	 */
2183 	v_decr_useonly(vp);
2184 	vp->v_iflag |= VI_OWEINACT;
2185 	if (VOP_ISLOCKED(vp, NULL) != LK_EXCLUSIVE) {
2186 		error = VOP_LOCK(vp, LK_EXCLUPGRADE|LK_INTERLOCK|LK_NOWAIT, td);
2187 		VI_LOCK(vp);
2188 		if (error) {
2189 			if (vp->v_usecount > 0)
2190 				vp->v_iflag &= ~VI_OWEINACT;
2191 			goto done;
2192 		}
2193 	}
2194 	if (vp->v_usecount > 0)
2195 		vp->v_iflag &= ~VI_OWEINACT;
2196 	if (vp->v_iflag & VI_OWEINACT)
2197 		vinactive(vp, td);
2198 	VOP_UNLOCK(vp, 0, td);
2199 done:
2200 	vdropl(vp);
2201 }
2202 
2203 /*
2204  * Somebody doesn't want the vnode recycled.
2205  */
2206 void
2207 vhold(struct vnode *vp)
2208 {
2209 
2210 	VI_LOCK(vp);
2211 	vholdl(vp);
2212 	VI_UNLOCK(vp);
2213 }
2214 
2215 void
2216 vholdl(struct vnode *vp)
2217 {
2218 
2219 	vp->v_holdcnt++;
2220 	if (VSHOULDBUSY(vp))
2221 		vbusy(vp);
2222 }
2223 
2224 /*
2225  * Note that there is one less who cares about this vnode.  vdrop() is the
2226  * opposite of vhold().
2227  */
2228 void
2229 vdrop(struct vnode *vp)
2230 {
2231 
2232 	VI_LOCK(vp);
2233 	vdropl(vp);
2234 }
2235 
2236 /*
2237  * Drop the hold count of the vnode.  If this is the last reference to
2238  * the vnode we will free it if it has been vgone'd otherwise it is
2239  * placed on the free list.
2240  */
2241 void
2242 vdropl(struct vnode *vp)
2243 {
2244 
2245 	ASSERT_VI_LOCKED(vp, "vdropl");
2246 	if (vp->v_holdcnt <= 0)
2247 		panic("vdrop: holdcnt %d", vp->v_holdcnt);
2248 	vp->v_holdcnt--;
2249 	if (vp->v_holdcnt == 0) {
2250 		if (vp->v_iflag & VI_DOOMED) {
2251 			vdestroy(vp);
2252 			return;
2253 		} else
2254 			vfree(vp);
2255 	}
2256 	VI_UNLOCK(vp);
2257 }
2258 
2259 /*
2260  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2261  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2262  * OWEINACT tracks whether a vnode missed a call to inactive due to a
2263  * failed lock upgrade.
2264  */
2265 static void
2266 vinactive(struct vnode *vp, struct thread *td)
2267 {
2268 
2269 	ASSERT_VOP_LOCKED(vp, "vinactive");
2270 	ASSERT_VI_LOCKED(vp, "vinactive");
2271 	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2272 	    ("vinactive: recursed on VI_DOINGINACT"));
2273 	vp->v_iflag |= VI_DOINGINACT;
2274 	vp->v_iflag &= ~VI_OWEINACT;
2275 	VI_UNLOCK(vp);
2276 	VOP_INACTIVE(vp, td);
2277 	VI_LOCK(vp);
2278 	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2279 	    ("vinactive: lost VI_DOINGINACT"));
2280 	vp->v_iflag &= ~VI_DOINGINACT;
2281 }
2282 
2283 /*
2284  * Remove any vnodes in the vnode table belonging to mount point mp.
2285  *
2286  * If FORCECLOSE is not specified, there should not be any active ones,
2287  * return error if any are found (nb: this is a user error, not a
2288  * system error). If FORCECLOSE is specified, detach any active vnodes
2289  * that are found.
2290  *
2291  * If WRITECLOSE is set, only flush out regular file vnodes open for
2292  * writing.
2293  *
2294  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2295  *
2296  * `rootrefs' specifies the base reference count for the root vnode
2297  * of this filesystem. The root vnode is considered busy if its
2298  * v_usecount exceeds this value. On a successful return, vflush(, td)
2299  * will call vrele() on the root vnode exactly rootrefs times.
2300  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2301  * be zero.
2302  */
2303 #ifdef DIAGNOSTIC
2304 static int busyprt = 0;		/* print out busy vnodes */
2305 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2306 #endif
2307 
2308 int
2309 vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
2310 {
2311 	struct vnode *vp, *mvp, *rootvp = NULL;
2312 	struct vattr vattr;
2313 	int busy = 0, error;
2314 
2315 	CTR1(KTR_VFS, "vflush: mp %p", mp);
2316 	if (rootrefs > 0) {
2317 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2318 		    ("vflush: bad args"));
2319 		/*
2320 		 * Get the filesystem root vnode. We can vput() it
2321 		 * immediately, since with rootrefs > 0, it won't go away.
2322 		 */
2323 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp, td)) != 0)
2324 			return (error);
2325 		vput(rootvp);
2326 
2327 	}
2328 	MNT_ILOCK(mp);
2329 loop:
2330 	MNT_VNODE_FOREACH(vp, mp, mvp) {
2331 
2332 		VI_LOCK(vp);
2333 		vholdl(vp);
2334 		MNT_IUNLOCK(mp);
2335 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE, td);
2336 		if (error) {
2337 			vdrop(vp);
2338 			MNT_ILOCK(mp);
2339 			MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2340 			goto loop;
2341 		}
2342 		/*
2343 		 * Skip over a vnodes marked VV_SYSTEM.
2344 		 */
2345 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2346 			VOP_UNLOCK(vp, 0, td);
2347 			vdrop(vp);
2348 			MNT_ILOCK(mp);
2349 			continue;
2350 		}
2351 		/*
2352 		 * If WRITECLOSE is set, flush out unlinked but still open
2353 		 * files (even if open only for reading) and regular file
2354 		 * vnodes open for writing.
2355 		 */
2356 		if (flags & WRITECLOSE) {
2357 			error = VOP_GETATTR(vp, &vattr, td->td_ucred, td);
2358 			VI_LOCK(vp);
2359 
2360 			if ((vp->v_type == VNON ||
2361 			    (error == 0 && vattr.va_nlink > 0)) &&
2362 			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2363 				VOP_UNLOCK(vp, 0, td);
2364 				vdropl(vp);
2365 				MNT_ILOCK(mp);
2366 				continue;
2367 			}
2368 		} else
2369 			VI_LOCK(vp);
2370 		/*
2371 		 * With v_usecount == 0, all we need to do is clear out the
2372 		 * vnode data structures and we are done.
2373 		 *
2374 		 * If FORCECLOSE is set, forcibly close the vnode.
2375 		 */
2376 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2377 			VNASSERT(vp->v_usecount == 0 ||
2378 			    (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2379 			    ("device VNODE %p is FORCECLOSED", vp));
2380 			vgonel(vp);
2381 		} else {
2382 			busy++;
2383 #ifdef DIAGNOSTIC
2384 			if (busyprt)
2385 				vprint("vflush: busy vnode", vp);
2386 #endif
2387 		}
2388 		VOP_UNLOCK(vp, 0, td);
2389 		vdropl(vp);
2390 		MNT_ILOCK(mp);
2391 	}
2392 	MNT_IUNLOCK(mp);
2393 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2394 		/*
2395 		 * If just the root vnode is busy, and if its refcount
2396 		 * is equal to `rootrefs', then go ahead and kill it.
2397 		 */
2398 		VI_LOCK(rootvp);
2399 		KASSERT(busy > 0, ("vflush: not busy"));
2400 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2401 		    ("vflush: usecount %d < rootrefs %d",
2402 		     rootvp->v_usecount, rootrefs));
2403 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2404 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK, td);
2405 			vgone(rootvp);
2406 			VOP_UNLOCK(rootvp, 0, td);
2407 			busy = 0;
2408 		} else
2409 			VI_UNLOCK(rootvp);
2410 	}
2411 	if (busy)
2412 		return (EBUSY);
2413 	for (; rootrefs > 0; rootrefs--)
2414 		vrele(rootvp);
2415 	return (0);
2416 }
2417 
2418 /*
2419  * Recycle an unused vnode to the front of the free list.
2420  */
2421 int
2422 vrecycle(struct vnode *vp, struct thread *td)
2423 {
2424 	int recycled;
2425 
2426 	ASSERT_VOP_LOCKED(vp, "vrecycle");
2427 	recycled = 0;
2428 	VI_LOCK(vp);
2429 	if (vp->v_usecount == 0) {
2430 		recycled = 1;
2431 		vgonel(vp);
2432 	}
2433 	VI_UNLOCK(vp);
2434 	return (recycled);
2435 }
2436 
2437 /*
2438  * Eliminate all activity associated with a vnode
2439  * in preparation for reuse.
2440  */
2441 void
2442 vgone(struct vnode *vp)
2443 {
2444 	VI_LOCK(vp);
2445 	vgonel(vp);
2446 	VI_UNLOCK(vp);
2447 }
2448 
2449 /*
2450  * vgone, with the vp interlock held.
2451  */
2452 void
2453 vgonel(struct vnode *vp)
2454 {
2455 	struct thread *td;
2456 	int oweinact;
2457 	int active;
2458 	struct mount *mp;
2459 
2460 	CTR1(KTR_VFS, "vgonel: vp %p", vp);
2461 	ASSERT_VOP_LOCKED(vp, "vgonel");
2462 	ASSERT_VI_LOCKED(vp, "vgonel");
2463 	VNASSERT(vp->v_holdcnt, vp,
2464 	    ("vgonel: vp %p has no reference.", vp));
2465 	td = curthread;
2466 
2467 	/*
2468 	 * Don't vgonel if we're already doomed.
2469 	 */
2470 	if (vp->v_iflag & VI_DOOMED)
2471 		return;
2472 	vp->v_iflag |= VI_DOOMED;
2473 	/*
2474 	 * Check to see if the vnode is in use.  If so, we have to call
2475 	 * VOP_CLOSE() and VOP_INACTIVE().
2476 	 */
2477 	active = vp->v_usecount;
2478 	oweinact = (vp->v_iflag & VI_OWEINACT);
2479 	VI_UNLOCK(vp);
2480 	/*
2481 	 * Clean out any buffers associated with the vnode.
2482 	 * If the flush fails, just toss the buffers.
2483 	 */
2484 	mp = NULL;
2485 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2486 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
2487 	if (vinvalbuf(vp, V_SAVE, td, 0, 0) != 0)
2488 		vinvalbuf(vp, 0, td, 0, 0);
2489 
2490 	/*
2491 	 * If purging an active vnode, it must be closed and
2492 	 * deactivated before being reclaimed.
2493 	 */
2494 	if (active)
2495 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2496 	if (oweinact || active) {
2497 		VI_LOCK(vp);
2498 		if ((vp->v_iflag & VI_DOINGINACT) == 0)
2499 			vinactive(vp, td);
2500 		VI_UNLOCK(vp);
2501 	}
2502 	/*
2503 	 * Reclaim the vnode.
2504 	 */
2505 	if (VOP_RECLAIM(vp, td))
2506 		panic("vgone: cannot reclaim");
2507 	if (mp != NULL)
2508 		vn_finished_secondary_write(mp);
2509 	VNASSERT(vp->v_object == NULL, vp,
2510 	    ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2511 	/*
2512 	 * Delete from old mount point vnode list.
2513 	 */
2514 	delmntque(vp);
2515 	cache_purge(vp);
2516 	/*
2517 	 * Done with purge, reset to the standard lock and invalidate
2518 	 * the vnode.
2519 	 */
2520 	VI_LOCK(vp);
2521 	vp->v_vnlock = &vp->v_lock;
2522 	vp->v_op = &dead_vnodeops;
2523 	vp->v_tag = "none";
2524 	vp->v_type = VBAD;
2525 }
2526 
2527 /*
2528  * Calculate the total number of references to a special device.
2529  */
2530 int
2531 vcount(struct vnode *vp)
2532 {
2533 	int count;
2534 
2535 	dev_lock();
2536 	count = vp->v_rdev->si_usecount;
2537 	dev_unlock();
2538 	return (count);
2539 }
2540 
2541 /*
2542  * Same as above, but using the struct cdev *as argument
2543  */
2544 int
2545 count_dev(struct cdev *dev)
2546 {
2547 	int count;
2548 
2549 	dev_lock();
2550 	count = dev->si_usecount;
2551 	dev_unlock();
2552 	return(count);
2553 }
2554 
2555 /*
2556  * Print out a description of a vnode.
2557  */
2558 static char *typename[] =
2559 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2560  "VMARKER"};
2561 
2562 void
2563 vn_printf(struct vnode *vp, const char *fmt, ...)
2564 {
2565 	va_list ap;
2566 	char buf[96];
2567 
2568 	va_start(ap, fmt);
2569 	vprintf(fmt, ap);
2570 	va_end(ap);
2571 	printf("%p: ", (void *)vp);
2572 	printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2573 	printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2574 	    vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2575 	buf[0] = '\0';
2576 	buf[1] = '\0';
2577 	if (vp->v_vflag & VV_ROOT)
2578 		strcat(buf, "|VV_ROOT");
2579 	if (vp->v_vflag & VV_TEXT)
2580 		strcat(buf, "|VV_TEXT");
2581 	if (vp->v_vflag & VV_SYSTEM)
2582 		strcat(buf, "|VV_SYSTEM");
2583 	if (vp->v_vflag & VV_DELETED)
2584 		strcat(buf, "|VV_DELETED");
2585 	if (vp->v_iflag & VI_DOOMED)
2586 		strcat(buf, "|VI_DOOMED");
2587 	if (vp->v_iflag & VI_FREE)
2588 		strcat(buf, "|VI_FREE");
2589 	printf("    flags (%s)\n", buf + 1);
2590 	if (mtx_owned(VI_MTX(vp)))
2591 		printf(" VI_LOCKed");
2592 	if (vp->v_object != NULL)
2593 		printf("    v_object %p ref %d pages %d\n",
2594 		    vp->v_object, vp->v_object->ref_count,
2595 		    vp->v_object->resident_page_count);
2596 	printf("    ");
2597 	lockmgr_printinfo(vp->v_vnlock);
2598 	printf("\n");
2599 	if (vp->v_data != NULL)
2600 		VOP_PRINT(vp);
2601 }
2602 
2603 #ifdef DDB
2604 /*
2605  * List all of the locked vnodes in the system.
2606  * Called when debugging the kernel.
2607  */
2608 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2609 {
2610 	struct mount *mp, *nmp;
2611 	struct vnode *vp;
2612 
2613 	/*
2614 	 * Note: because this is DDB, we can't obey the locking semantics
2615 	 * for these structures, which means we could catch an inconsistent
2616 	 * state and dereference a nasty pointer.  Not much to be done
2617 	 * about that.
2618 	 */
2619 	printf("Locked vnodes\n");
2620 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2621 		nmp = TAILQ_NEXT(mp, mnt_list);
2622 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2623 			if (vp->v_type != VMARKER && VOP_ISLOCKED(vp, NULL))
2624 				vprint("", vp);
2625 		}
2626 		nmp = TAILQ_NEXT(mp, mnt_list);
2627 	}
2628 }
2629 
2630 /*
2631  * Show details about the given vnode.
2632  */
2633 DB_SHOW_COMMAND(vnode, db_show_vnode)
2634 {
2635 	struct vnode *vp;
2636 
2637 	if (!have_addr)
2638 		return;
2639 	vp = (struct vnode *)addr;
2640 	vn_printf(vp, "vnode ");
2641 }
2642 #endif	/* DDB */
2643 
2644 /*
2645  * Fill in a struct xvfsconf based on a struct vfsconf.
2646  */
2647 static void
2648 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2649 {
2650 
2651 	strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2652 	xvfsp->vfc_typenum = vfsp->vfc_typenum;
2653 	xvfsp->vfc_refcount = vfsp->vfc_refcount;
2654 	xvfsp->vfc_flags = vfsp->vfc_flags;
2655 	/*
2656 	 * These are unused in userland, we keep them
2657 	 * to not break binary compatibility.
2658 	 */
2659 	xvfsp->vfc_vfsops = NULL;
2660 	xvfsp->vfc_next = NULL;
2661 }
2662 
2663 /*
2664  * Top level filesystem related information gathering.
2665  */
2666 static int
2667 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2668 {
2669 	struct vfsconf *vfsp;
2670 	struct xvfsconf xvfsp;
2671 	int error;
2672 
2673 	error = 0;
2674 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2675 		bzero(&xvfsp, sizeof(xvfsp));
2676 		vfsconf2x(vfsp, &xvfsp);
2677 		error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
2678 		if (error)
2679 			break;
2680 	}
2681 	return (error);
2682 }
2683 
2684 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2685     "S,xvfsconf", "List of all configured filesystems");
2686 
2687 #ifndef BURN_BRIDGES
2688 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2689 
2690 static int
2691 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2692 {
2693 	int *name = (int *)arg1 - 1;	/* XXX */
2694 	u_int namelen = arg2 + 1;	/* XXX */
2695 	struct vfsconf *vfsp;
2696 	struct xvfsconf xvfsp;
2697 
2698 	printf("WARNING: userland calling deprecated sysctl, "
2699 	    "please rebuild world\n");
2700 
2701 #if 1 || defined(COMPAT_PRELITE2)
2702 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2703 	if (namelen == 1)
2704 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2705 #endif
2706 
2707 	switch (name[1]) {
2708 	case VFS_MAXTYPENUM:
2709 		if (namelen != 2)
2710 			return (ENOTDIR);
2711 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2712 	case VFS_CONF:
2713 		if (namelen != 3)
2714 			return (ENOTDIR);	/* overloaded */
2715 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
2716 			if (vfsp->vfc_typenum == name[2])
2717 				break;
2718 		if (vfsp == NULL)
2719 			return (EOPNOTSUPP);
2720 		bzero(&xvfsp, sizeof(xvfsp));
2721 		vfsconf2x(vfsp, &xvfsp);
2722 		return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
2723 	}
2724 	return (EOPNOTSUPP);
2725 }
2726 
2727 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
2728 	vfs_sysctl, "Generic filesystem");
2729 
2730 #if 1 || defined(COMPAT_PRELITE2)
2731 
2732 static int
2733 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2734 {
2735 	int error;
2736 	struct vfsconf *vfsp;
2737 	struct ovfsconf ovfs;
2738 
2739 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2740 		bzero(&ovfs, sizeof(ovfs));
2741 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2742 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2743 		ovfs.vfc_index = vfsp->vfc_typenum;
2744 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2745 		ovfs.vfc_flags = vfsp->vfc_flags;
2746 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2747 		if (error)
2748 			return error;
2749 	}
2750 	return 0;
2751 }
2752 
2753 #endif /* 1 || COMPAT_PRELITE2 */
2754 #endif /* !BURN_BRIDGES */
2755 
2756 #define KINFO_VNODESLOP		10
2757 #ifdef notyet
2758 /*
2759  * Dump vnode list (via sysctl).
2760  */
2761 /* ARGSUSED */
2762 static int
2763 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2764 {
2765 	struct xvnode *xvn;
2766 	struct thread *td = req->td;
2767 	struct mount *mp;
2768 	struct vnode *vp;
2769 	int error, len, n;
2770 
2771 	/*
2772 	 * Stale numvnodes access is not fatal here.
2773 	 */
2774 	req->lock = 0;
2775 	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
2776 	if (!req->oldptr)
2777 		/* Make an estimate */
2778 		return (SYSCTL_OUT(req, 0, len));
2779 
2780 	error = sysctl_wire_old_buffer(req, 0);
2781 	if (error != 0)
2782 		return (error);
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 		MNT_ILOCK(mp);
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 			xvn[n].xv_id = 0;	/* XXX compat */
2797 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
2798 			XV_COPY(usecount);
2799 			XV_COPY(writecount);
2800 			XV_COPY(holdcnt);
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 				break;
2812 			case VBLK:
2813 			case VCHR:
2814 				if (vp->v_rdev == NULL) {
2815 					vrele(vp);
2816 					continue;
2817 				}
2818 				xvn[n].xv_dev = dev2udev(vp->v_rdev);
2819 				break;
2820 			case VSOCK:
2821 				xvn[n].xv_socket = vp->v_socket;
2822 				break;
2823 			case VFIFO:
2824 				xvn[n].xv_fifo = vp->v_fifoinfo;
2825 				break;
2826 			case VNON:
2827 			case VBAD:
2828 			default:
2829 				/* shouldn't happen? */
2830 				vrele(vp);
2831 				continue;
2832 			}
2833 			vrele(vp);
2834 			++n;
2835 		}
2836 		MNT_IUNLOCK(mp);
2837 		mtx_lock(&mountlist_mtx);
2838 		vfs_unbusy(mp, td);
2839 		if (n == len)
2840 			break;
2841 	}
2842 	mtx_unlock(&mountlist_mtx);
2843 
2844 	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
2845 	free(xvn, M_TEMP);
2846 	return (error);
2847 }
2848 
2849 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2850 	0, 0, sysctl_vnode, "S,xvnode", "");
2851 #endif
2852 
2853 /*
2854  * Unmount all filesystems. The list is traversed in reverse order
2855  * of mounting to avoid dependencies.
2856  */
2857 void
2858 vfs_unmountall(void)
2859 {
2860 	struct mount *mp;
2861 	struct thread *td;
2862 	int error;
2863 
2864 	KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
2865 	td = curthread;
2866 	/*
2867 	 * Since this only runs when rebooting, it is not interlocked.
2868 	 */
2869 	while(!TAILQ_EMPTY(&mountlist)) {
2870 		mp = TAILQ_LAST(&mountlist, mntlist);
2871 		error = dounmount(mp, MNT_FORCE, td);
2872 		if (error) {
2873 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
2874 			/*
2875 			 * XXX: Due to the way in which we mount the root
2876 			 * file system off of devfs, devfs will generate a
2877 			 * "busy" warning when we try to unmount it before
2878 			 * the root.  Don't print a warning as a result in
2879 			 * order to avoid false positive errors that may
2880 			 * cause needless upset.
2881 			 */
2882 			if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
2883 				printf("unmount of %s failed (",
2884 				    mp->mnt_stat.f_mntonname);
2885 				if (error == EBUSY)
2886 					printf("BUSY)\n");
2887 				else
2888 					printf("%d)\n", error);
2889 			}
2890 		} else {
2891 			/* The unmount has removed mp from the mountlist */
2892 		}
2893 	}
2894 }
2895 
2896 /*
2897  * perform msync on all vnodes under a mount point
2898  * the mount point must be locked.
2899  */
2900 void
2901 vfs_msync(struct mount *mp, int flags)
2902 {
2903 	struct vnode *vp, *mvp;
2904 	struct vm_object *obj;
2905 
2906 	MNT_ILOCK(mp);
2907 	MNT_VNODE_FOREACH(vp, mp, mvp) {
2908 		VI_LOCK(vp);
2909 		if ((vp->v_iflag & VI_OBJDIRTY) &&
2910 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2911 			MNT_IUNLOCK(mp);
2912 			if (!vget(vp,
2913 			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
2914 			    curthread)) {
2915 				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
2916 					vput(vp);
2917 					MNT_ILOCK(mp);
2918 					continue;
2919 				}
2920 
2921 				obj = vp->v_object;
2922 				if (obj != NULL) {
2923 					VM_OBJECT_LOCK(obj);
2924 					vm_object_page_clean(obj, 0, 0,
2925 					    flags == MNT_WAIT ?
2926 					    OBJPC_SYNC : OBJPC_NOSYNC);
2927 					VM_OBJECT_UNLOCK(obj);
2928 				}
2929 				vput(vp);
2930 			}
2931 			MNT_ILOCK(mp);
2932 		} else
2933 			VI_UNLOCK(vp);
2934 	}
2935 	MNT_IUNLOCK(mp);
2936 }
2937 
2938 /*
2939  * Mark a vnode as free, putting it up for recycling.
2940  */
2941 static void
2942 vfree(struct vnode *vp)
2943 {
2944 
2945 	CTR1(KTR_VFS, "vfree vp %p", vp);
2946 	ASSERT_VI_LOCKED(vp, "vfree");
2947 	mtx_lock(&vnode_free_list_mtx);
2948 	VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
2949 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
2950 	VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
2951 	VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
2952 	    ("vfree: Freeing doomed vnode"));
2953 	if (vp->v_iflag & VI_AGE) {
2954 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2955 	} else {
2956 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2957 	}
2958 	freevnodes++;
2959 	vp->v_iflag &= ~VI_AGE;
2960 	vp->v_iflag |= VI_FREE;
2961 	mtx_unlock(&vnode_free_list_mtx);
2962 }
2963 
2964 /*
2965  * Opposite of vfree() - mark a vnode as in use.
2966  */
2967 static void
2968 vbusy(struct vnode *vp)
2969 {
2970 	CTR1(KTR_VFS, "vbusy vp %p", vp);
2971 	ASSERT_VI_LOCKED(vp, "vbusy");
2972 	VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
2973 	VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
2974 
2975 	mtx_lock(&vnode_free_list_mtx);
2976 	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2977 	freevnodes--;
2978 	vp->v_iflag &= ~(VI_FREE|VI_AGE);
2979 	mtx_unlock(&vnode_free_list_mtx);
2980 }
2981 
2982 /*
2983  * Initalize per-vnode helper structure to hold poll-related state.
2984  */
2985 void
2986 v_addpollinfo(struct vnode *vp)
2987 {
2988 	struct vpollinfo *vi;
2989 
2990 	vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
2991 	if (vp->v_pollinfo != NULL) {
2992 		uma_zfree(vnodepoll_zone, vi);
2993 		return;
2994 	}
2995 	vp->v_pollinfo = vi;
2996 	mtx_init(&vp->v_pollinfo->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
2997 	knlist_init(&vp->v_pollinfo->vpi_selinfo.si_note, vp, vfs_knllock,
2998 	    vfs_knlunlock, vfs_knllocked);
2999 }
3000 
3001 /*
3002  * Record a process's interest in events which might happen to
3003  * a vnode.  Because poll uses the historic select-style interface
3004  * internally, this routine serves as both the ``check for any
3005  * pending events'' and the ``record my interest in future events''
3006  * functions.  (These are done together, while the lock is held,
3007  * to avoid race conditions.)
3008  */
3009 int
3010 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3011 {
3012 
3013 	if (vp->v_pollinfo == NULL)
3014 		v_addpollinfo(vp);
3015 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3016 	if (vp->v_pollinfo->vpi_revents & events) {
3017 		/*
3018 		 * This leaves events we are not interested
3019 		 * in available for the other process which
3020 		 * which presumably had requested them
3021 		 * (otherwise they would never have been
3022 		 * recorded).
3023 		 */
3024 		events &= vp->v_pollinfo->vpi_revents;
3025 		vp->v_pollinfo->vpi_revents &= ~events;
3026 
3027 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3028 		return events;
3029 	}
3030 	vp->v_pollinfo->vpi_events |= events;
3031 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3032 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3033 	return 0;
3034 }
3035 
3036 /*
3037  * Routine to create and manage a filesystem syncer vnode.
3038  */
3039 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3040 static int	sync_fsync(struct  vop_fsync_args *);
3041 static int	sync_inactive(struct  vop_inactive_args *);
3042 static int	sync_reclaim(struct  vop_reclaim_args *);
3043 
3044 static struct vop_vector sync_vnodeops = {
3045 	.vop_bypass =	VOP_EOPNOTSUPP,
3046 	.vop_close =	sync_close,		/* close */
3047 	.vop_fsync =	sync_fsync,		/* fsync */
3048 	.vop_inactive =	sync_inactive,	/* inactive */
3049 	.vop_reclaim =	sync_reclaim,	/* reclaim */
3050 	.vop_lock1 =	vop_stdlock,	/* lock */
3051 	.vop_unlock =	vop_stdunlock,	/* unlock */
3052 	.vop_islocked =	vop_stdislocked,	/* islocked */
3053 };
3054 
3055 /*
3056  * Create a new filesystem syncer vnode for the specified mount point.
3057  */
3058 int
3059 vfs_allocate_syncvnode(struct mount *mp)
3060 {
3061 	struct vnode *vp;
3062 	static long start, incr, next;
3063 	int error;
3064 
3065 	/* Allocate a new vnode */
3066 	if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
3067 		mp->mnt_syncer = NULL;
3068 		return (error);
3069 	}
3070 	vp->v_type = VNON;
3071 	error = insmntque(vp, mp);
3072 	if (error != 0)
3073 		panic("vfs_allocate_syncvnode: insmntque failed");
3074 	/*
3075 	 * Place the vnode onto the syncer worklist. We attempt to
3076 	 * scatter them about on the list so that they will go off
3077 	 * at evenly distributed times even if all the filesystems
3078 	 * are mounted at once.
3079 	 */
3080 	next += incr;
3081 	if (next == 0 || next > syncer_maxdelay) {
3082 		start /= 2;
3083 		incr /= 2;
3084 		if (start == 0) {
3085 			start = syncer_maxdelay / 2;
3086 			incr = syncer_maxdelay;
3087 		}
3088 		next = start;
3089 	}
3090 	VI_LOCK(vp);
3091 	vn_syncer_add_to_worklist(&vp->v_bufobj,
3092 	    syncdelay > 0 ? next % syncdelay : 0);
3093 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3094 	mtx_lock(&sync_mtx);
3095 	sync_vnode_count++;
3096 	mtx_unlock(&sync_mtx);
3097 	VI_UNLOCK(vp);
3098 	mp->mnt_syncer = vp;
3099 	return (0);
3100 }
3101 
3102 /*
3103  * Do a lazy sync of the filesystem.
3104  */
3105 static int
3106 sync_fsync(struct vop_fsync_args *ap)
3107 {
3108 	struct vnode *syncvp = ap->a_vp;
3109 	struct mount *mp = syncvp->v_mount;
3110 	struct thread *td = ap->a_td;
3111 	int error;
3112 	struct bufobj *bo;
3113 
3114 	/*
3115 	 * We only need to do something if this is a lazy evaluation.
3116 	 */
3117 	if (ap->a_waitfor != MNT_LAZY)
3118 		return (0);
3119 
3120 	/*
3121 	 * Move ourselves to the back of the sync list.
3122 	 */
3123 	bo = &syncvp->v_bufobj;
3124 	BO_LOCK(bo);
3125 	vn_syncer_add_to_worklist(bo, syncdelay);
3126 	BO_UNLOCK(bo);
3127 
3128 	/*
3129 	 * Walk the list of vnodes pushing all that are dirty and
3130 	 * not already on the sync list.
3131 	 */
3132 	mtx_lock(&mountlist_mtx);
3133 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
3134 		mtx_unlock(&mountlist_mtx);
3135 		return (0);
3136 	}
3137 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3138 		vfs_unbusy(mp, td);
3139 		return (0);
3140 	}
3141 	MNT_ILOCK(mp);
3142 	mp->mnt_noasync++;
3143 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
3144 	MNT_IUNLOCK(mp);
3145 	vfs_msync(mp, MNT_NOWAIT);
3146 	error = VFS_SYNC(mp, MNT_LAZY, td);
3147 	MNT_ILOCK(mp);
3148 	mp->mnt_noasync--;
3149 	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3150 		mp->mnt_kern_flag |= MNTK_ASYNC;
3151 	MNT_IUNLOCK(mp);
3152 	vn_finished_write(mp);
3153 	vfs_unbusy(mp, td);
3154 	return (error);
3155 }
3156 
3157 /*
3158  * The syncer vnode is no referenced.
3159  */
3160 static int
3161 sync_inactive(struct vop_inactive_args *ap)
3162 {
3163 
3164 	vgone(ap->a_vp);
3165 	return (0);
3166 }
3167 
3168 /*
3169  * The syncer vnode is no longer needed and is being decommissioned.
3170  *
3171  * Modifications to the worklist must be protected by sync_mtx.
3172  */
3173 static int
3174 sync_reclaim(struct vop_reclaim_args *ap)
3175 {
3176 	struct vnode *vp = ap->a_vp;
3177 	struct bufobj *bo;
3178 
3179 	VI_LOCK(vp);
3180 	bo = &vp->v_bufobj;
3181 	vp->v_mount->mnt_syncer = NULL;
3182 	if (bo->bo_flag & BO_ONWORKLST) {
3183 		mtx_lock(&sync_mtx);
3184 		LIST_REMOVE(bo, bo_synclist);
3185 		syncer_worklist_len--;
3186 		sync_vnode_count--;
3187 		mtx_unlock(&sync_mtx);
3188 		bo->bo_flag &= ~BO_ONWORKLST;
3189 	}
3190 	VI_UNLOCK(vp);
3191 
3192 	return (0);
3193 }
3194 
3195 /*
3196  * Check if vnode represents a disk device
3197  */
3198 int
3199 vn_isdisk(struct vnode *vp, int *errp)
3200 {
3201 	int error;
3202 
3203 	error = 0;
3204 	dev_lock();
3205 	if (vp->v_type != VCHR)
3206 		error = ENOTBLK;
3207 	else if (vp->v_rdev == NULL)
3208 		error = ENXIO;
3209 	else if (vp->v_rdev->si_devsw == NULL)
3210 		error = ENXIO;
3211 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3212 		error = ENOTBLK;
3213 	dev_unlock();
3214 	if (errp != NULL)
3215 		*errp = error;
3216 	return (error == 0);
3217 }
3218 
3219 /*
3220  * Common filesystem object access control check routine.  Accepts a
3221  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3222  * and optional call-by-reference privused argument allowing vaccess()
3223  * to indicate to the caller whether privilege was used to satisfy the
3224  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3225  *
3226  * The ifdef'd CAPABILITIES version is here for reference, but is not
3227  * actually used.
3228  */
3229 int
3230 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3231     mode_t acc_mode, struct ucred *cred, int *privused)
3232 {
3233 	mode_t dac_granted;
3234 	mode_t priv_granted;
3235 
3236 	/*
3237 	 * Look for a normal, non-privileged way to access the file/directory
3238 	 * as requested.  If it exists, go with that.
3239 	 */
3240 
3241 	if (privused != NULL)
3242 		*privused = 0;
3243 
3244 	dac_granted = 0;
3245 
3246 	/* Check the owner. */
3247 	if (cred->cr_uid == file_uid) {
3248 		dac_granted |= VADMIN;
3249 		if (file_mode & S_IXUSR)
3250 			dac_granted |= VEXEC;
3251 		if (file_mode & S_IRUSR)
3252 			dac_granted |= VREAD;
3253 		if (file_mode & S_IWUSR)
3254 			dac_granted |= (VWRITE | VAPPEND);
3255 
3256 		if ((acc_mode & dac_granted) == acc_mode)
3257 			return (0);
3258 
3259 		goto privcheck;
3260 	}
3261 
3262 	/* Otherwise, check the groups (first match) */
3263 	if (groupmember(file_gid, cred)) {
3264 		if (file_mode & S_IXGRP)
3265 			dac_granted |= VEXEC;
3266 		if (file_mode & S_IRGRP)
3267 			dac_granted |= VREAD;
3268 		if (file_mode & S_IWGRP)
3269 			dac_granted |= (VWRITE | VAPPEND);
3270 
3271 		if ((acc_mode & dac_granted) == acc_mode)
3272 			return (0);
3273 
3274 		goto privcheck;
3275 	}
3276 
3277 	/* Otherwise, check everyone else. */
3278 	if (file_mode & S_IXOTH)
3279 		dac_granted |= VEXEC;
3280 	if (file_mode & S_IROTH)
3281 		dac_granted |= VREAD;
3282 	if (file_mode & S_IWOTH)
3283 		dac_granted |= (VWRITE | VAPPEND);
3284 	if ((acc_mode & dac_granted) == acc_mode)
3285 		return (0);
3286 
3287 privcheck:
3288 	/*
3289 	 * Build a privilege mask to determine if the set of privileges
3290 	 * satisfies the requirements when combined with the granted mask
3291 	 * from above.  For each privilege, if the privilege is required,
3292 	 * bitwise or the request type onto the priv_granted mask.
3293 	 */
3294 	priv_granted = 0;
3295 
3296 	if (type == VDIR) {
3297 		/*
3298 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3299 		 * requests, instead of PRIV_VFS_EXEC.
3300 		 */
3301 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3302 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3303 			priv_granted |= VEXEC;
3304 	} else {
3305 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3306 		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3307 			priv_granted |= VEXEC;
3308 	}
3309 
3310 	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3311 	    !priv_check_cred(cred, PRIV_VFS_READ, 0))
3312 		priv_granted |= VREAD;
3313 
3314 	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3315 	    !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3316 		priv_granted |= (VWRITE | VAPPEND);
3317 
3318 	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3319 	    !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3320 		priv_granted |= VADMIN;
3321 
3322 	if ((acc_mode & (priv_granted | dac_granted)) == acc_mode) {
3323 		/* XXX audit: privilege used */
3324 		if (privused != NULL)
3325 			*privused = 1;
3326 		return (0);
3327 	}
3328 
3329 	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3330 }
3331 
3332 /*
3333  * Credential check based on process requesting service, and per-attribute
3334  * permissions.
3335  */
3336 int
3337 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3338     struct thread *td, int access)
3339 {
3340 
3341 	/*
3342 	 * Kernel-invoked always succeeds.
3343 	 */
3344 	if (cred == NOCRED)
3345 		return (0);
3346 
3347 	/*
3348 	 * Do not allow privileged processes in jail to directly manipulate
3349 	 * system attributes.
3350 	 */
3351 	switch (attrnamespace) {
3352 	case EXTATTR_NAMESPACE_SYSTEM:
3353 		/* Potentially should be: return (EPERM); */
3354 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3355 	case EXTATTR_NAMESPACE_USER:
3356 		return (VOP_ACCESS(vp, access, cred, td));
3357 	default:
3358 		return (EPERM);
3359 	}
3360 }
3361 
3362 #ifdef DEBUG_VFS_LOCKS
3363 /*
3364  * This only exists to supress warnings from unlocked specfs accesses.  It is
3365  * no longer ok to have an unlocked VFS.
3366  */
3367 #define	IGNORE_LOCK(vp) ((vp)->v_type == VCHR || (vp)->v_type == VBAD)
3368 
3369 int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
3370 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
3371 
3372 int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
3373 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
3374 
3375 int vfs_badlock_print = 1;	/* Print lock violations. */
3376 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
3377 
3378 #ifdef KDB
3379 int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
3380 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
3381 #endif
3382 
3383 static void
3384 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3385 {
3386 
3387 #ifdef KDB
3388 	if (vfs_badlock_backtrace)
3389 		kdb_backtrace();
3390 #endif
3391 	if (vfs_badlock_print)
3392 		printf("%s: %p %s\n", str, (void *)vp, msg);
3393 	if (vfs_badlock_ddb)
3394 		kdb_enter("lock violation");
3395 }
3396 
3397 void
3398 assert_vi_locked(struct vnode *vp, const char *str)
3399 {
3400 
3401 	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3402 		vfs_badlock("interlock is not locked but should be", str, vp);
3403 }
3404 
3405 void
3406 assert_vi_unlocked(struct vnode *vp, const char *str)
3407 {
3408 
3409 	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3410 		vfs_badlock("interlock is locked but should not be", str, vp);
3411 }
3412 
3413 void
3414 assert_vop_locked(struct vnode *vp, const char *str)
3415 {
3416 
3417 	if (vp && !IGNORE_LOCK(vp) && VOP_ISLOCKED(vp, NULL) == 0)
3418 		vfs_badlock("is not locked but should be", str, vp);
3419 }
3420 
3421 void
3422 assert_vop_unlocked(struct vnode *vp, const char *str)
3423 {
3424 
3425 	if (vp && !IGNORE_LOCK(vp) &&
3426 	    VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE)
3427 		vfs_badlock("is locked but should not be", str, vp);
3428 }
3429 
3430 void
3431 assert_vop_elocked(struct vnode *vp, const char *str)
3432 {
3433 
3434 	if (vp && !IGNORE_LOCK(vp) &&
3435 	    VOP_ISLOCKED(vp, curthread) != LK_EXCLUSIVE)
3436 		vfs_badlock("is not exclusive locked but should be", str, vp);
3437 }
3438 
3439 #if 0
3440 void
3441 assert_vop_elocked_other(struct vnode *vp, const char *str)
3442 {
3443 
3444 	if (vp && !IGNORE_LOCK(vp) &&
3445 	    VOP_ISLOCKED(vp, curthread) != LK_EXCLOTHER)
3446 		vfs_badlock("is not exclusive locked by another thread",
3447 		    str, vp);
3448 }
3449 
3450 void
3451 assert_vop_slocked(struct vnode *vp, const char *str)
3452 {
3453 
3454 	if (vp && !IGNORE_LOCK(vp) &&
3455 	    VOP_ISLOCKED(vp, curthread) != LK_SHARED)
3456 		vfs_badlock("is not locked shared but should be", str, vp);
3457 }
3458 #endif /* 0 */
3459 #endif /* DEBUG_VFS_LOCKS */
3460 
3461 void
3462 vop_rename_pre(void *ap)
3463 {
3464 	struct vop_rename_args *a = ap;
3465 
3466 #ifdef DEBUG_VFS_LOCKS
3467 	if (a->a_tvp)
3468 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3469 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3470 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3471 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3472 
3473 	/* Check the source (from). */
3474 	if (a->a_tdvp != a->a_fdvp && a->a_tvp != a->a_fdvp)
3475 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3476 	if (a->a_tvp != a->a_fvp)
3477 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3478 
3479 	/* Check the target. */
3480 	if (a->a_tvp)
3481 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3482 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3483 #endif
3484 	if (a->a_tdvp != a->a_fdvp)
3485 		vhold(a->a_fdvp);
3486 	if (a->a_tvp != a->a_fvp)
3487 		vhold(a->a_fvp);
3488 	vhold(a->a_tdvp);
3489 	if (a->a_tvp)
3490 		vhold(a->a_tvp);
3491 }
3492 
3493 void
3494 vop_strategy_pre(void *ap)
3495 {
3496 #ifdef DEBUG_VFS_LOCKS
3497 	struct vop_strategy_args *a;
3498 	struct buf *bp;
3499 
3500 	a = ap;
3501 	bp = a->a_bp;
3502 
3503 	/*
3504 	 * Cluster ops lock their component buffers but not the IO container.
3505 	 */
3506 	if ((bp->b_flags & B_CLUSTER) != 0)
3507 		return;
3508 
3509 	if (BUF_REFCNT(bp) < 1) {
3510 		if (vfs_badlock_print)
3511 			printf(
3512 			    "VOP_STRATEGY: bp is not locked but should be\n");
3513 		if (vfs_badlock_ddb)
3514 			kdb_enter("lock violation");
3515 	}
3516 #endif
3517 }
3518 
3519 void
3520 vop_lookup_pre(void *ap)
3521 {
3522 #ifdef DEBUG_VFS_LOCKS
3523 	struct vop_lookup_args *a;
3524 	struct vnode *dvp;
3525 
3526 	a = ap;
3527 	dvp = a->a_dvp;
3528 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3529 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3530 #endif
3531 }
3532 
3533 void
3534 vop_lookup_post(void *ap, int rc)
3535 {
3536 #ifdef DEBUG_VFS_LOCKS
3537 	struct vop_lookup_args *a;
3538 	struct vnode *dvp;
3539 	struct vnode *vp;
3540 
3541 	a = ap;
3542 	dvp = a->a_dvp;
3543 	vp = *(a->a_vpp);
3544 
3545 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3546 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3547 
3548 	if (!rc)
3549 		ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3550 #endif
3551 }
3552 
3553 void
3554 vop_lock_pre(void *ap)
3555 {
3556 #ifdef DEBUG_VFS_LOCKS
3557 	struct vop_lock1_args *a = ap;
3558 
3559 	if ((a->a_flags & LK_INTERLOCK) == 0)
3560 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3561 	else
3562 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3563 #endif
3564 }
3565 
3566 void
3567 vop_lock_post(void *ap, int rc)
3568 {
3569 #ifdef DEBUG_VFS_LOCKS
3570 	struct vop_lock1_args *a = ap;
3571 
3572 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3573 	if (rc == 0)
3574 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
3575 #endif
3576 }
3577 
3578 void
3579 vop_unlock_pre(void *ap)
3580 {
3581 #ifdef DEBUG_VFS_LOCKS
3582 	struct vop_unlock_args *a = ap;
3583 
3584 	if (a->a_flags & LK_INTERLOCK)
3585 		ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
3586 	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
3587 #endif
3588 }
3589 
3590 void
3591 vop_unlock_post(void *ap, int rc)
3592 {
3593 #ifdef DEBUG_VFS_LOCKS
3594 	struct vop_unlock_args *a = ap;
3595 
3596 	if (a->a_flags & LK_INTERLOCK)
3597 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
3598 #endif
3599 }
3600 
3601 void
3602 vop_create_post(void *ap, int rc)
3603 {
3604 	struct vop_create_args *a = ap;
3605 
3606 	if (!rc)
3607 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3608 }
3609 
3610 void
3611 vop_link_post(void *ap, int rc)
3612 {
3613 	struct vop_link_args *a = ap;
3614 
3615 	if (!rc) {
3616 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
3617 		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
3618 	}
3619 }
3620 
3621 void
3622 vop_mkdir_post(void *ap, int rc)
3623 {
3624 	struct vop_mkdir_args *a = ap;
3625 
3626 	if (!rc)
3627 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3628 }
3629 
3630 void
3631 vop_mknod_post(void *ap, int rc)
3632 {
3633 	struct vop_mknod_args *a = ap;
3634 
3635 	if (!rc)
3636 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3637 }
3638 
3639 void
3640 vop_remove_post(void *ap, int rc)
3641 {
3642 	struct vop_remove_args *a = ap;
3643 
3644 	if (!rc) {
3645 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3646 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3647 	}
3648 }
3649 
3650 void
3651 vop_rename_post(void *ap, int rc)
3652 {
3653 	struct vop_rename_args *a = ap;
3654 
3655 	if (!rc) {
3656 		VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
3657 		VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
3658 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
3659 		if (a->a_tvp)
3660 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
3661 	}
3662 	if (a->a_tdvp != a->a_fdvp)
3663 		vdrop(a->a_fdvp);
3664 	if (a->a_tvp != a->a_fvp)
3665 		vdrop(a->a_fvp);
3666 	vdrop(a->a_tdvp);
3667 	if (a->a_tvp)
3668 		vdrop(a->a_tvp);
3669 }
3670 
3671 void
3672 vop_rmdir_post(void *ap, int rc)
3673 {
3674 	struct vop_rmdir_args *a = ap;
3675 
3676 	if (!rc) {
3677 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3678 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3679 	}
3680 }
3681 
3682 void
3683 vop_setattr_post(void *ap, int rc)
3684 {
3685 	struct vop_setattr_args *a = ap;
3686 
3687 	if (!rc)
3688 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
3689 }
3690 
3691 void
3692 vop_symlink_post(void *ap, int rc)
3693 {
3694 	struct vop_symlink_args *a = ap;
3695 
3696 	if (!rc)
3697 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3698 }
3699 
3700 static struct knlist fs_knlist;
3701 
3702 static void
3703 vfs_event_init(void *arg)
3704 {
3705 	knlist_init(&fs_knlist, NULL, NULL, NULL, NULL);
3706 }
3707 /* XXX - correct order? */
3708 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
3709 
3710 void
3711 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
3712 {
3713 
3714 	KNOTE_UNLOCKED(&fs_knlist, event);
3715 }
3716 
3717 static int	filt_fsattach(struct knote *kn);
3718 static void	filt_fsdetach(struct knote *kn);
3719 static int	filt_fsevent(struct knote *kn, long hint);
3720 
3721 struct filterops fs_filtops =
3722 	{ 0, filt_fsattach, filt_fsdetach, filt_fsevent };
3723 
3724 static int
3725 filt_fsattach(struct knote *kn)
3726 {
3727 
3728 	kn->kn_flags |= EV_CLEAR;
3729 	knlist_add(&fs_knlist, kn, 0);
3730 	return (0);
3731 }
3732 
3733 static void
3734 filt_fsdetach(struct knote *kn)
3735 {
3736 
3737 	knlist_remove(&fs_knlist, kn, 0);
3738 }
3739 
3740 static int
3741 filt_fsevent(struct knote *kn, long hint)
3742 {
3743 
3744 	kn->kn_fflags |= hint;
3745 	return (kn->kn_fflags != 0);
3746 }
3747 
3748 static int
3749 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
3750 {
3751 	struct vfsidctl vc;
3752 	int error;
3753 	struct mount *mp;
3754 
3755 	error = SYSCTL_IN(req, &vc, sizeof(vc));
3756 	if (error)
3757 		return (error);
3758 	if (vc.vc_vers != VFS_CTL_VERS1)
3759 		return (EINVAL);
3760 	mp = vfs_getvfs(&vc.vc_fsid);
3761 	if (mp == NULL)
3762 		return (ENOENT);
3763 	/* ensure that a specific sysctl goes to the right filesystem. */
3764 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
3765 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
3766 		vfs_rel(mp);
3767 		return (EINVAL);
3768 	}
3769 	VCTLTOREQ(&vc, req);
3770 	error = VFS_SYSCTL(mp, vc.vc_op, req);
3771 	vfs_rel(mp);
3772 	return (error);
3773 }
3774 
3775 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
3776     "Sysctl by fsid");
3777 
3778 /*
3779  * Function to initialize a va_filerev field sensibly.
3780  * XXX: Wouldn't a random number make a lot more sense ??
3781  */
3782 u_quad_t
3783 init_va_filerev(void)
3784 {
3785 	struct bintime bt;
3786 
3787 	getbinuptime(&bt);
3788 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
3789 }
3790 
3791 static int	filt_vfsread(struct knote *kn, long hint);
3792 static int	filt_vfswrite(struct knote *kn, long hint);
3793 static int	filt_vfsvnode(struct knote *kn, long hint);
3794 static void	filt_vfsdetach(struct knote *kn);
3795 static struct filterops vfsread_filtops =
3796 	{ 1, NULL, filt_vfsdetach, filt_vfsread };
3797 static struct filterops vfswrite_filtops =
3798 	{ 1, NULL, filt_vfsdetach, filt_vfswrite };
3799 static struct filterops vfsvnode_filtops =
3800 	{ 1, NULL, filt_vfsdetach, filt_vfsvnode };
3801 
3802 static void
3803 vfs_knllock(void *arg)
3804 {
3805 	struct vnode *vp = arg;
3806 
3807 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
3808 }
3809 
3810 static void
3811 vfs_knlunlock(void *arg)
3812 {
3813 	struct vnode *vp = arg;
3814 
3815 	VOP_UNLOCK(vp, 0, curthread);
3816 }
3817 
3818 static int
3819 vfs_knllocked(void *arg)
3820 {
3821 	struct vnode *vp = arg;
3822 
3823 	return (VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE);
3824 }
3825 
3826 int
3827 vfs_kqfilter(struct vop_kqfilter_args *ap)
3828 {
3829 	struct vnode *vp = ap->a_vp;
3830 	struct knote *kn = ap->a_kn;
3831 	struct knlist *knl;
3832 
3833 	switch (kn->kn_filter) {
3834 	case EVFILT_READ:
3835 		kn->kn_fop = &vfsread_filtops;
3836 		break;
3837 	case EVFILT_WRITE:
3838 		kn->kn_fop = &vfswrite_filtops;
3839 		break;
3840 	case EVFILT_VNODE:
3841 		kn->kn_fop = &vfsvnode_filtops;
3842 		break;
3843 	default:
3844 		return (EINVAL);
3845 	}
3846 
3847 	kn->kn_hook = (caddr_t)vp;
3848 
3849 	if (vp->v_pollinfo == NULL)
3850 		v_addpollinfo(vp);
3851 	if (vp->v_pollinfo == NULL)
3852 		return (ENOMEM);
3853 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
3854 	knlist_add(knl, kn, 0);
3855 
3856 	return (0);
3857 }
3858 
3859 /*
3860  * Detach knote from vnode
3861  */
3862 static void
3863 filt_vfsdetach(struct knote *kn)
3864 {
3865 	struct vnode *vp = (struct vnode *)kn->kn_hook;
3866 
3867 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
3868 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
3869 }
3870 
3871 /*ARGSUSED*/
3872 static int
3873 filt_vfsread(struct knote *kn, long hint)
3874 {
3875 	struct vnode *vp = (struct vnode *)kn->kn_hook;
3876 	struct vattr va;
3877 
3878 	/*
3879 	 * filesystem is gone, so set the EOF flag and schedule
3880 	 * the knote for deletion.
3881 	 */
3882 	if (hint == NOTE_REVOKE) {
3883 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3884 		return (1);
3885 	}
3886 
3887 	if (VOP_GETATTR(vp, &va, curthread->td_ucred, curthread))
3888 		return (0);
3889 
3890 	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
3891 	return (kn->kn_data != 0);
3892 }
3893 
3894 /*ARGSUSED*/
3895 static int
3896 filt_vfswrite(struct knote *kn, long hint)
3897 {
3898 	/*
3899 	 * filesystem is gone, so set the EOF flag and schedule
3900 	 * the knote for deletion.
3901 	 */
3902 	if (hint == NOTE_REVOKE)
3903 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3904 
3905 	kn->kn_data = 0;
3906 	return (1);
3907 }
3908 
3909 static int
3910 filt_vfsvnode(struct knote *kn, long hint)
3911 {
3912 	if (kn->kn_sfflags & hint)
3913 		kn->kn_fflags |= hint;
3914 	if (hint == NOTE_REVOKE) {
3915 		kn->kn_flags |= EV_EOF;
3916 		return (1);
3917 	}
3918 	return (kn->kn_fflags != 0);
3919 }
3920 
3921 int
3922 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
3923 {
3924 	int error;
3925 
3926 	if (dp->d_reclen > ap->a_uio->uio_resid)
3927 		return (ENAMETOOLONG);
3928 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
3929 	if (error) {
3930 		if (ap->a_ncookies != NULL) {
3931 			if (ap->a_cookies != NULL)
3932 				free(ap->a_cookies, M_TEMP);
3933 			ap->a_cookies = NULL;
3934 			*ap->a_ncookies = 0;
3935 		}
3936 		return (error);
3937 	}
3938 	if (ap->a_ncookies == NULL)
3939 		return (0);
3940 
3941 	KASSERT(ap->a_cookies,
3942 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
3943 
3944 	*ap->a_cookies = realloc(*ap->a_cookies,
3945 	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
3946 	(*ap->a_cookies)[*ap->a_ncookies] = off;
3947 	return (0);
3948 }
3949 
3950 /*
3951  * Mark for update the access time of the file if the filesystem
3952  * supports VA_MARK_ATIME.  This functionality is used by execve
3953  * and mmap, so we want to avoid the synchronous I/O implied by
3954  * directly setting va_atime for the sake of efficiency.
3955  */
3956 void
3957 vfs_mark_atime(struct vnode *vp, struct thread *td)
3958 {
3959 	struct vattr atimeattr;
3960 
3961 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
3962 		VATTR_NULL(&atimeattr);
3963 		atimeattr.va_vaflags |= VA_MARK_ATIME;
3964 		(void)VOP_SETATTR(vp, &atimeattr, td->td_ucred, td);
3965 	}
3966 }
3967