xref: /freebsd/sys/kern/vfs_subr.c (revision 531c890b8aecbf157fe3491503b5ca62c0b01093)
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)))
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);
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)) {
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);
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);
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 = curthread;
722 
723 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
724 	    SHUTDOWN_PRI_FIRST);
725 
726 	mtx_lock(&Giant);
727 
728 	for (;;) {
729 		kproc_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_vnode_destroy(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 mount *vnmp;
840 
841 	CTR1(KTR_VFS, "vtryrecycle: trying vp %p", vp);
842 	VNASSERT(vp->v_holdcnt, vp,
843 	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
844 	/*
845 	 * This vnode may found and locked via some other list, if so we
846 	 * can't recycle it yet.
847 	 */
848 	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
849 		return (EWOULDBLOCK);
850 	/*
851 	 * Don't recycle if its filesystem is being suspended.
852 	 */
853 	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
854 		VOP_UNLOCK(vp, 0);
855 		return (EBUSY);
856 	}
857 	/*
858 	 * If we got this far, we need to acquire the interlock and see if
859 	 * anyone picked up this vnode from another list.  If not, we will
860 	 * mark it with DOOMED via vgonel() so that anyone who does find it
861 	 * will skip over it.
862 	 */
863 	VI_LOCK(vp);
864 	if (vp->v_usecount) {
865 		VOP_UNLOCK(vp, LK_INTERLOCK);
866 		vn_finished_write(vnmp);
867 		return (EBUSY);
868 	}
869 	if ((vp->v_iflag & VI_DOOMED) == 0)
870 		vgonel(vp);
871 	VOP_UNLOCK(vp, LK_INTERLOCK);
872 	vn_finished_write(vnmp);
873 	CTR1(KTR_VFS, "vtryrecycle: recycled vp %p", vp);
874 	return (0);
875 }
876 
877 /*
878  * Return the next vnode from the free list.
879  */
880 int
881 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
882     struct vnode **vpp)
883 {
884 	struct vnode *vp = NULL;
885 	struct bufobj *bo;
886 
887 	mtx_lock(&vnode_free_list_mtx);
888 	/*
889 	 * Lend our context to reclaim vnodes if they've exceeded the max.
890 	 */
891 	if (freevnodes > wantfreevnodes)
892 		vnlru_free(1);
893 	/*
894 	 * Wait for available vnodes.
895 	 */
896 	if (numvnodes > desiredvnodes) {
897 		if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
898 			/*
899 			 * File system is beeing suspended, we cannot risk a
900 			 * deadlock here, so allocate new vnode anyway.
901 			 */
902 			if (freevnodes > wantfreevnodes)
903 				vnlru_free(freevnodes - wantfreevnodes);
904 			goto alloc;
905 		}
906 		if (vnlruproc_sig == 0) {
907 			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
908 			wakeup(vnlruproc);
909 		}
910 		msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
911 		    "vlruwk", hz);
912 #if 0	/* XXX Not all VFS_VGET/ffs_vget callers check returns. */
913 		if (numvnodes > desiredvnodes) {
914 			mtx_unlock(&vnode_free_list_mtx);
915 			return (ENFILE);
916 		}
917 #endif
918 	}
919 alloc:
920 	numvnodes++;
921 	mtx_unlock(&vnode_free_list_mtx);
922 	vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
923 	/*
924 	 * Setup locks.
925 	 */
926 	vp->v_vnlock = &vp->v_lock;
927 	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
928 	/*
929 	 * By default, don't allow shared locks unless filesystems
930 	 * opt-in.
931 	 */
932 	lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
933 	/*
934 	 * Initialize bufobj.
935 	 */
936 	bo = &vp->v_bufobj;
937 	bo->__bo_vnode = vp;
938 	bo->bo_mtx = &vp->v_interlock;
939 	bo->bo_ops = &buf_ops_bio;
940 	bo->bo_private = vp;
941 	TAILQ_INIT(&bo->bo_clean.bv_hd);
942 	TAILQ_INIT(&bo->bo_dirty.bv_hd);
943 	/*
944 	 * Initialize namecache.
945 	 */
946 	LIST_INIT(&vp->v_cache_src);
947 	TAILQ_INIT(&vp->v_cache_dst);
948 	/*
949 	 * Finalize various vnode identity bits.
950 	 */
951 	vp->v_type = VNON;
952 	vp->v_tag = tag;
953 	vp->v_op = vops;
954 	v_incr_usecount(vp);
955 	vp->v_data = 0;
956 #ifdef MAC
957 	mac_vnode_init(vp);
958 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
959 		mac_vnode_associate_singlelabel(mp, vp);
960 	else if (mp == NULL)
961 		printf("NULL mp in getnewvnode()\n");
962 #endif
963 	if (mp != NULL) {
964 		bo->bo_bsize = mp->mnt_stat.f_iosize;
965 		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
966 			vp->v_vflag |= VV_NOKNOTE;
967 	}
968 
969 	CTR2(KTR_VFS, "getnewvnode: mp %p vp %p", mp, vp);
970 	*vpp = vp;
971 	return (0);
972 }
973 
974 /*
975  * Delete from old mount point vnode list, if on one.
976  */
977 static void
978 delmntque(struct vnode *vp)
979 {
980 	struct mount *mp;
981 
982 	mp = vp->v_mount;
983 	if (mp == NULL)
984 		return;
985 	MNT_ILOCK(mp);
986 	vp->v_mount = NULL;
987 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
988 		("bad mount point vnode list size"));
989 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
990 	mp->mnt_nvnodelistsize--;
991 	MNT_REL(mp);
992 	MNT_IUNLOCK(mp);
993 }
994 
995 static void
996 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
997 {
998 
999 	vp->v_data = NULL;
1000 	vp->v_op = &dead_vnodeops;
1001 	/* XXX non mp-safe fs may still call insmntque with vnode
1002 	   unlocked */
1003 	if (!VOP_ISLOCKED(vp))
1004 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1005 	vgone(vp);
1006 	vput(vp);
1007 }
1008 
1009 /*
1010  * Insert into list of vnodes for the new mount point, if available.
1011  */
1012 int
1013 insmntque1(struct vnode *vp, struct mount *mp,
1014 	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1015 {
1016 
1017 	KASSERT(vp->v_mount == NULL,
1018 		("insmntque: vnode already on per mount vnode list"));
1019 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1020 	MNT_ILOCK(mp);
1021 	if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1022 	    mp->mnt_nvnodelistsize == 0) {
1023 		MNT_IUNLOCK(mp);
1024 		if (dtr != NULL)
1025 			dtr(vp, dtr_arg);
1026 		return (EBUSY);
1027 	}
1028 	vp->v_mount = mp;
1029 	MNT_REF(mp);
1030 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1031 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1032 		("neg mount point vnode list size"));
1033 	mp->mnt_nvnodelistsize++;
1034 	MNT_IUNLOCK(mp);
1035 	return (0);
1036 }
1037 
1038 int
1039 insmntque(struct vnode *vp, struct mount *mp)
1040 {
1041 
1042 	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1043 }
1044 
1045 /*
1046  * Flush out and invalidate all buffers associated with a bufobj
1047  * Called with the underlying object locked.
1048  */
1049 int
1050 bufobj_invalbuf(struct bufobj *bo, int flags, struct thread *td, int slpflag,
1051     int slptimeo)
1052 {
1053 	int error;
1054 
1055 	BO_LOCK(bo);
1056 	if (flags & V_SAVE) {
1057 		error = bufobj_wwait(bo, slpflag, slptimeo);
1058 		if (error) {
1059 			BO_UNLOCK(bo);
1060 			return (error);
1061 		}
1062 		if (bo->bo_dirty.bv_cnt > 0) {
1063 			BO_UNLOCK(bo);
1064 			if ((error = BO_SYNC(bo, MNT_WAIT, td)) != 0)
1065 				return (error);
1066 			/*
1067 			 * XXX We could save a lock/unlock if this was only
1068 			 * enabled under INVARIANTS
1069 			 */
1070 			BO_LOCK(bo);
1071 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1072 				panic("vinvalbuf: dirty bufs");
1073 		}
1074 	}
1075 	/*
1076 	 * If you alter this loop please notice that interlock is dropped and
1077 	 * reacquired in flushbuflist.  Special care is needed to ensure that
1078 	 * no race conditions occur from this.
1079 	 */
1080 	do {
1081 		error = flushbuflist(&bo->bo_clean,
1082 		    flags, bo, slpflag, slptimeo);
1083 		if (error == 0)
1084 			error = flushbuflist(&bo->bo_dirty,
1085 			    flags, bo, slpflag, slptimeo);
1086 		if (error != 0 && error != EAGAIN) {
1087 			BO_UNLOCK(bo);
1088 			return (error);
1089 		}
1090 	} while (error != 0);
1091 
1092 	/*
1093 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1094 	 * have write I/O in-progress but if there is a VM object then the
1095 	 * VM object can also have read-I/O in-progress.
1096 	 */
1097 	do {
1098 		bufobj_wwait(bo, 0, 0);
1099 		BO_UNLOCK(bo);
1100 		if (bo->bo_object != NULL) {
1101 			VM_OBJECT_LOCK(bo->bo_object);
1102 			vm_object_pip_wait(bo->bo_object, "bovlbx");
1103 			VM_OBJECT_UNLOCK(bo->bo_object);
1104 		}
1105 		BO_LOCK(bo);
1106 	} while (bo->bo_numoutput > 0);
1107 	BO_UNLOCK(bo);
1108 
1109 	/*
1110 	 * Destroy the copy in the VM cache, too.
1111 	 */
1112 	if (bo->bo_object != NULL) {
1113 		VM_OBJECT_LOCK(bo->bo_object);
1114 		vm_object_page_remove(bo->bo_object, 0, 0,
1115 			(flags & V_SAVE) ? TRUE : FALSE);
1116 		VM_OBJECT_UNLOCK(bo->bo_object);
1117 	}
1118 
1119 #ifdef INVARIANTS
1120 	BO_LOCK(bo);
1121 	if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1122 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1123 		panic("vinvalbuf: flush failed");
1124 	BO_UNLOCK(bo);
1125 #endif
1126 	return (0);
1127 }
1128 
1129 /*
1130  * Flush out and invalidate all buffers associated with a vnode.
1131  * Called with the underlying object locked.
1132  */
1133 int
1134 vinvalbuf(struct vnode *vp, int flags, struct thread *td, int slpflag,
1135     int slptimeo)
1136 {
1137 
1138 	CTR2(KTR_VFS, "vinvalbuf vp %p flags %d", vp, flags);
1139 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1140 	return (bufobj_invalbuf(&vp->v_bufobj, flags, td, slpflag, slptimeo));
1141 }
1142 
1143 /*
1144  * Flush out buffers on the specified list.
1145  *
1146  */
1147 static int
1148 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1149     int slptimeo)
1150 {
1151 	struct buf *bp, *nbp;
1152 	int retval, error;
1153 	daddr_t lblkno;
1154 	b_xflags_t xflags;
1155 
1156 	ASSERT_BO_LOCKED(bo);
1157 
1158 	retval = 0;
1159 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1160 		if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1161 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1162 			continue;
1163 		}
1164 		lblkno = 0;
1165 		xflags = 0;
1166 		if (nbp != NULL) {
1167 			lblkno = nbp->b_lblkno;
1168 			xflags = nbp->b_xflags &
1169 				(BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1170 		}
1171 		retval = EAGAIN;
1172 		error = BUF_TIMELOCK(bp,
1173 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1174 		    "flushbuf", slpflag, slptimeo);
1175 		if (error) {
1176 			BO_LOCK(bo);
1177 			return (error != ENOLCK ? error : EAGAIN);
1178 		}
1179 		KASSERT(bp->b_bufobj == bo,
1180 		    ("bp %p wrong b_bufobj %p should be %p",
1181 		    bp, bp->b_bufobj, bo));
1182 		if (bp->b_bufobj != bo) {	/* XXX: necessary ? */
1183 			BUF_UNLOCK(bp);
1184 			BO_LOCK(bo);
1185 			return (EAGAIN);
1186 		}
1187 		/*
1188 		 * XXX Since there are no node locks for NFS, I
1189 		 * believe there is a slight chance that a delayed
1190 		 * write will occur while sleeping just above, so
1191 		 * check for it.
1192 		 */
1193 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1194 		    (flags & V_SAVE)) {
1195 			bremfree(bp);
1196 			bp->b_flags |= B_ASYNC;
1197 			bwrite(bp);
1198 			BO_LOCK(bo);
1199 			return (EAGAIN);	/* XXX: why not loop ? */
1200 		}
1201 		bremfree(bp);
1202 		bp->b_flags |= (B_INVAL | B_RELBUF);
1203 		bp->b_flags &= ~B_ASYNC;
1204 		brelse(bp);
1205 		BO_LOCK(bo);
1206 		if (nbp != NULL &&
1207 		    (nbp->b_bufobj != bo ||
1208 		     nbp->b_lblkno != lblkno ||
1209 		     (nbp->b_xflags &
1210 		      (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1211 			break;			/* nbp invalid */
1212 	}
1213 	return (retval);
1214 }
1215 
1216 /*
1217  * Truncate a file's buffer and pages to a specified length.  This
1218  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1219  * sync activity.
1220  */
1221 int
1222 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1223     off_t length, int blksize)
1224 {
1225 	struct buf *bp, *nbp;
1226 	int anyfreed;
1227 	int trunclbn;
1228 	struct bufobj *bo;
1229 
1230 	CTR2(KTR_VFS, "vtruncbuf vp %p length %jd", vp, length);
1231 	/*
1232 	 * Round up to the *next* lbn.
1233 	 */
1234 	trunclbn = (length + blksize - 1) / blksize;
1235 
1236 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1237 restart:
1238 	VI_LOCK(vp);
1239 	bo = &vp->v_bufobj;
1240 	anyfreed = 1;
1241 	for (;anyfreed;) {
1242 		anyfreed = 0;
1243 		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1244 			if (bp->b_lblkno < trunclbn)
1245 				continue;
1246 			if (BUF_LOCK(bp,
1247 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1248 			    VI_MTX(vp)) == ENOLCK)
1249 				goto restart;
1250 
1251 			bremfree(bp);
1252 			bp->b_flags |= (B_INVAL | B_RELBUF);
1253 			bp->b_flags &= ~B_ASYNC;
1254 			brelse(bp);
1255 			anyfreed = 1;
1256 
1257 			if (nbp != NULL &&
1258 			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1259 			    (nbp->b_vp != vp) ||
1260 			    (nbp->b_flags & B_DELWRI))) {
1261 				goto restart;
1262 			}
1263 			VI_LOCK(vp);
1264 		}
1265 
1266 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1267 			if (bp->b_lblkno < trunclbn)
1268 				continue;
1269 			if (BUF_LOCK(bp,
1270 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1271 			    VI_MTX(vp)) == ENOLCK)
1272 				goto restart;
1273 			bremfree(bp);
1274 			bp->b_flags |= (B_INVAL | B_RELBUF);
1275 			bp->b_flags &= ~B_ASYNC;
1276 			brelse(bp);
1277 			anyfreed = 1;
1278 			if (nbp != NULL &&
1279 			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1280 			    (nbp->b_vp != vp) ||
1281 			    (nbp->b_flags & B_DELWRI) == 0)) {
1282 				goto restart;
1283 			}
1284 			VI_LOCK(vp);
1285 		}
1286 	}
1287 
1288 	if (length > 0) {
1289 restartsync:
1290 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1291 			if (bp->b_lblkno > 0)
1292 				continue;
1293 			/*
1294 			 * Since we hold the vnode lock this should only
1295 			 * fail if we're racing with the buf daemon.
1296 			 */
1297 			if (BUF_LOCK(bp,
1298 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1299 			    VI_MTX(vp)) == ENOLCK) {
1300 				goto restart;
1301 			}
1302 			VNASSERT((bp->b_flags & B_DELWRI), vp,
1303 			    ("buf(%p) on dirty queue without DELWRI", bp));
1304 
1305 			bremfree(bp);
1306 			bawrite(bp);
1307 			VI_LOCK(vp);
1308 			goto restartsync;
1309 		}
1310 	}
1311 
1312 	bufobj_wwait(bo, 0, 0);
1313 	VI_UNLOCK(vp);
1314 	vnode_pager_setsize(vp, length);
1315 
1316 	return (0);
1317 }
1318 
1319 /*
1320  * buf_splay() - splay tree core for the clean/dirty list of buffers in
1321  * 		 a vnode.
1322  *
1323  *	NOTE: We have to deal with the special case of a background bitmap
1324  *	buffer, a situation where two buffers will have the same logical
1325  *	block offset.  We want (1) only the foreground buffer to be accessed
1326  *	in a lookup and (2) must differentiate between the foreground and
1327  *	background buffer in the splay tree algorithm because the splay
1328  *	tree cannot normally handle multiple entities with the same 'index'.
1329  *	We accomplish this by adding differentiating flags to the splay tree's
1330  *	numerical domain.
1331  */
1332 static
1333 struct buf *
1334 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1335 {
1336 	struct buf dummy;
1337 	struct buf *lefttreemax, *righttreemin, *y;
1338 
1339 	if (root == NULL)
1340 		return (NULL);
1341 	lefttreemax = righttreemin = &dummy;
1342 	for (;;) {
1343 		if (lblkno < root->b_lblkno ||
1344 		    (lblkno == root->b_lblkno &&
1345 		    (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1346 			if ((y = root->b_left) == NULL)
1347 				break;
1348 			if (lblkno < y->b_lblkno) {
1349 				/* Rotate right. */
1350 				root->b_left = y->b_right;
1351 				y->b_right = root;
1352 				root = y;
1353 				if ((y = root->b_left) == NULL)
1354 					break;
1355 			}
1356 			/* Link into the new root's right tree. */
1357 			righttreemin->b_left = root;
1358 			righttreemin = root;
1359 		} else if (lblkno > root->b_lblkno ||
1360 		    (lblkno == root->b_lblkno &&
1361 		    (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1362 			if ((y = root->b_right) == NULL)
1363 				break;
1364 			if (lblkno > y->b_lblkno) {
1365 				/* Rotate left. */
1366 				root->b_right = y->b_left;
1367 				y->b_left = root;
1368 				root = y;
1369 				if ((y = root->b_right) == NULL)
1370 					break;
1371 			}
1372 			/* Link into the new root's left tree. */
1373 			lefttreemax->b_right = root;
1374 			lefttreemax = root;
1375 		} else {
1376 			break;
1377 		}
1378 		root = y;
1379 	}
1380 	/* Assemble the new root. */
1381 	lefttreemax->b_right = root->b_left;
1382 	righttreemin->b_left = root->b_right;
1383 	root->b_left = dummy.b_right;
1384 	root->b_right = dummy.b_left;
1385 	return (root);
1386 }
1387 
1388 static void
1389 buf_vlist_remove(struct buf *bp)
1390 {
1391 	struct buf *root;
1392 	struct bufv *bv;
1393 
1394 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1395 	ASSERT_BO_LOCKED(bp->b_bufobj);
1396 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1397 	    (BX_VNDIRTY|BX_VNCLEAN),
1398 	    ("buf_vlist_remove: Buf %p is on two lists", bp));
1399 	if (bp->b_xflags & BX_VNDIRTY)
1400 		bv = &bp->b_bufobj->bo_dirty;
1401 	else
1402 		bv = &bp->b_bufobj->bo_clean;
1403 	if (bp != bv->bv_root) {
1404 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1405 		KASSERT(root == bp, ("splay lookup failed in remove"));
1406 	}
1407 	if (bp->b_left == NULL) {
1408 		root = bp->b_right;
1409 	} else {
1410 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1411 		root->b_right = bp->b_right;
1412 	}
1413 	bv->bv_root = root;
1414 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1415 	bv->bv_cnt--;
1416 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1417 }
1418 
1419 /*
1420  * Add the buffer to the sorted clean or dirty block list using a
1421  * splay tree algorithm.
1422  *
1423  * NOTE: xflags is passed as a constant, optimizing this inline function!
1424  */
1425 static void
1426 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1427 {
1428 	struct buf *root;
1429 	struct bufv *bv;
1430 
1431 	ASSERT_BO_LOCKED(bo);
1432 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1433 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1434 	bp->b_xflags |= xflags;
1435 	if (xflags & BX_VNDIRTY)
1436 		bv = &bo->bo_dirty;
1437 	else
1438 		bv = &bo->bo_clean;
1439 
1440 	root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1441 	if (root == NULL) {
1442 		bp->b_left = NULL;
1443 		bp->b_right = NULL;
1444 		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1445 	} else if (bp->b_lblkno < root->b_lblkno ||
1446 	    (bp->b_lblkno == root->b_lblkno &&
1447 	    (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1448 		bp->b_left = root->b_left;
1449 		bp->b_right = root;
1450 		root->b_left = NULL;
1451 		TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1452 	} else {
1453 		bp->b_right = root->b_right;
1454 		bp->b_left = root;
1455 		root->b_right = NULL;
1456 		TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1457 	}
1458 	bv->bv_cnt++;
1459 	bv->bv_root = bp;
1460 }
1461 
1462 /*
1463  * Lookup a buffer using the splay tree.  Note that we specifically avoid
1464  * shadow buffers used in background bitmap writes.
1465  *
1466  * This code isn't quite efficient as it could be because we are maintaining
1467  * two sorted lists and do not know which list the block resides in.
1468  *
1469  * During a "make buildworld" the desired buffer is found at one of
1470  * the roots more than 60% of the time.  Thus, checking both roots
1471  * before performing either splay eliminates unnecessary splays on the
1472  * first tree splayed.
1473  */
1474 struct buf *
1475 gbincore(struct bufobj *bo, daddr_t lblkno)
1476 {
1477 	struct buf *bp;
1478 
1479 	ASSERT_BO_LOCKED(bo);
1480 	if ((bp = bo->bo_clean.bv_root) != NULL &&
1481 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1482 		return (bp);
1483 	if ((bp = bo->bo_dirty.bv_root) != NULL &&
1484 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1485 		return (bp);
1486 	if ((bp = bo->bo_clean.bv_root) != NULL) {
1487 		bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1488 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1489 			return (bp);
1490 	}
1491 	if ((bp = bo->bo_dirty.bv_root) != NULL) {
1492 		bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1493 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1494 			return (bp);
1495 	}
1496 	return (NULL);
1497 }
1498 
1499 /*
1500  * Associate a buffer with a vnode.
1501  */
1502 void
1503 bgetvp(struct vnode *vp, struct buf *bp)
1504 {
1505 
1506 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1507 
1508 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1509 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1510 	    ("bgetvp: bp already attached! %p", bp));
1511 
1512 	ASSERT_VI_LOCKED(vp, "bgetvp");
1513 	vholdl(vp);
1514 	if (VFS_NEEDSGIANT(vp->v_mount) ||
1515 	    vp->v_bufobj.bo_flag & BO_NEEDSGIANT)
1516 		bp->b_flags |= B_NEEDSGIANT;
1517 	bp->b_vp = vp;
1518 	bp->b_bufobj = &vp->v_bufobj;
1519 	/*
1520 	 * Insert onto list for new vnode.
1521 	 */
1522 	buf_vlist_add(bp, &vp->v_bufobj, BX_VNCLEAN);
1523 }
1524 
1525 /*
1526  * Disassociate a buffer from a vnode.
1527  */
1528 void
1529 brelvp(struct buf *bp)
1530 {
1531 	struct bufobj *bo;
1532 	struct vnode *vp;
1533 
1534 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1535 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1536 
1537 	/*
1538 	 * Delete from old vnode list, if on one.
1539 	 */
1540 	vp = bp->b_vp;		/* XXX */
1541 	bo = bp->b_bufobj;
1542 	BO_LOCK(bo);
1543 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1544 		buf_vlist_remove(bp);
1545 	else
1546 		panic("brelvp: Buffer %p not on queue.", bp);
1547 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1548 		bo->bo_flag &= ~BO_ONWORKLST;
1549 		mtx_lock(&sync_mtx);
1550 		LIST_REMOVE(bo, bo_synclist);
1551 		syncer_worklist_len--;
1552 		mtx_unlock(&sync_mtx);
1553 	}
1554 	bp->b_flags &= ~B_NEEDSGIANT;
1555 	bp->b_vp = NULL;
1556 	bp->b_bufobj = NULL;
1557 	vdropl(vp);
1558 }
1559 
1560 /*
1561  * Add an item to the syncer work queue.
1562  */
1563 static void
1564 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1565 {
1566 	int slot;
1567 
1568 	ASSERT_BO_LOCKED(bo);
1569 
1570 	mtx_lock(&sync_mtx);
1571 	if (bo->bo_flag & BO_ONWORKLST)
1572 		LIST_REMOVE(bo, bo_synclist);
1573 	else {
1574 		bo->bo_flag |= BO_ONWORKLST;
1575 		syncer_worklist_len++;
1576 	}
1577 
1578 	if (delay > syncer_maxdelay - 2)
1579 		delay = syncer_maxdelay - 2;
1580 	slot = (syncer_delayno + delay) & syncer_mask;
1581 
1582 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
1583 	mtx_unlock(&sync_mtx);
1584 }
1585 
1586 static int
1587 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1588 {
1589 	int error, len;
1590 
1591 	mtx_lock(&sync_mtx);
1592 	len = syncer_worklist_len - sync_vnode_count;
1593 	mtx_unlock(&sync_mtx);
1594 	error = SYSCTL_OUT(req, &len, sizeof(len));
1595 	return (error);
1596 }
1597 
1598 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1599     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1600 
1601 static struct proc *updateproc;
1602 static void sched_sync(void);
1603 static struct kproc_desc up_kp = {
1604 	"syncer",
1605 	sched_sync,
1606 	&updateproc
1607 };
1608 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1609 
1610 static int
1611 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1612 {
1613 	struct vnode *vp;
1614 	struct mount *mp;
1615 	int vfslocked;
1616 
1617 	vfslocked = 0;
1618 restart:
1619 	*bo = LIST_FIRST(slp);
1620 	if (*bo == NULL) {
1621 		VFS_UNLOCK_GIANT(vfslocked);
1622 		return (0);
1623 	}
1624 	vp = (*bo)->__bo_vnode;	/* XXX */
1625 	if (VFS_NEEDSGIANT(vp->v_mount)) {
1626 		if (!vfslocked) {
1627 			vfslocked = 1;
1628 			if (mtx_trylock(&Giant) == 0) {
1629 				mtx_unlock(&sync_mtx);
1630 				mtx_lock(&Giant);
1631 				mtx_lock(&sync_mtx);
1632 				goto restart;
1633 			}
1634 		}
1635 	} else {
1636 		VFS_UNLOCK_GIANT(vfslocked);
1637 		vfslocked = 0;
1638 	}
1639 	if (VOP_ISLOCKED(vp) != 0) {
1640 		VFS_UNLOCK_GIANT(vfslocked);
1641 		return (1);
1642 	}
1643 	if (VI_TRYLOCK(vp) == 0) {
1644 		VFS_UNLOCK_GIANT(vfslocked);
1645 		return (1);
1646 	}
1647 	/*
1648 	 * We use vhold in case the vnode does not
1649 	 * successfully sync.  vhold prevents the vnode from
1650 	 * going away when we unlock the sync_mtx so that
1651 	 * we can acquire the vnode interlock.
1652 	 */
1653 	vholdl(vp);
1654 	mtx_unlock(&sync_mtx);
1655 	VI_UNLOCK(vp);
1656 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1657 		vdrop(vp);
1658 		VFS_UNLOCK_GIANT(vfslocked);
1659 		mtx_lock(&sync_mtx);
1660 		return (1);
1661 	}
1662 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1663 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
1664 	VOP_UNLOCK(vp, 0);
1665 	vn_finished_write(mp);
1666 	VI_LOCK(vp);
1667 	if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1668 		/*
1669 		 * Put us back on the worklist.  The worklist
1670 		 * routine will remove us from our current
1671 		 * position and then add us back in at a later
1672 		 * position.
1673 		 */
1674 		vn_syncer_add_to_worklist(*bo, syncdelay);
1675 	}
1676 	vdropl(vp);
1677 	VFS_UNLOCK_GIANT(vfslocked);
1678 	mtx_lock(&sync_mtx);
1679 	return (0);
1680 }
1681 
1682 /*
1683  * System filesystem synchronizer daemon.
1684  */
1685 static void
1686 sched_sync(void)
1687 {
1688 	struct synclist *next;
1689 	struct synclist *slp;
1690 	struct bufobj *bo;
1691 	long starttime;
1692 	struct thread *td = curthread;
1693 	static int dummychan;
1694 	int last_work_seen;
1695 	int net_worklist_len;
1696 	int syncer_final_iter;
1697 	int first_printf;
1698 	int error;
1699 
1700 	last_work_seen = 0;
1701 	syncer_final_iter = 0;
1702 	first_printf = 1;
1703 	syncer_state = SYNCER_RUNNING;
1704 	starttime = time_uptime;
1705 	td->td_pflags |= TDP_NORUNNINGBUF;
1706 
1707 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1708 	    SHUTDOWN_PRI_LAST);
1709 
1710 	mtx_lock(&sync_mtx);
1711 	for (;;) {
1712 		if (syncer_state == SYNCER_FINAL_DELAY &&
1713 		    syncer_final_iter == 0) {
1714 			mtx_unlock(&sync_mtx);
1715 			kproc_suspend_check(td->td_proc);
1716 			mtx_lock(&sync_mtx);
1717 		}
1718 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
1719 		if (syncer_state != SYNCER_RUNNING &&
1720 		    starttime != time_uptime) {
1721 			if (first_printf) {
1722 				printf("\nSyncing disks, vnodes remaining...");
1723 				first_printf = 0;
1724 			}
1725 			printf("%d ", net_worklist_len);
1726 		}
1727 		starttime = time_uptime;
1728 
1729 		/*
1730 		 * Push files whose dirty time has expired.  Be careful
1731 		 * of interrupt race on slp queue.
1732 		 *
1733 		 * Skip over empty worklist slots when shutting down.
1734 		 */
1735 		do {
1736 			slp = &syncer_workitem_pending[syncer_delayno];
1737 			syncer_delayno += 1;
1738 			if (syncer_delayno == syncer_maxdelay)
1739 				syncer_delayno = 0;
1740 			next = &syncer_workitem_pending[syncer_delayno];
1741 			/*
1742 			 * If the worklist has wrapped since the
1743 			 * it was emptied of all but syncer vnodes,
1744 			 * switch to the FINAL_DELAY state and run
1745 			 * for one more second.
1746 			 */
1747 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
1748 			    net_worklist_len == 0 &&
1749 			    last_work_seen == syncer_delayno) {
1750 				syncer_state = SYNCER_FINAL_DELAY;
1751 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1752 			}
1753 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1754 		    syncer_worklist_len > 0);
1755 
1756 		/*
1757 		 * Keep track of the last time there was anything
1758 		 * on the worklist other than syncer vnodes.
1759 		 * Return to the SHUTTING_DOWN state if any
1760 		 * new work appears.
1761 		 */
1762 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1763 			last_work_seen = syncer_delayno;
1764 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1765 			syncer_state = SYNCER_SHUTTING_DOWN;
1766 		while (!LIST_EMPTY(slp)) {
1767 			error = sync_vnode(slp, &bo, td);
1768 			if (error == 1) {
1769 				LIST_REMOVE(bo, bo_synclist);
1770 				LIST_INSERT_HEAD(next, bo, bo_synclist);
1771 				continue;
1772 			}
1773 		}
1774 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1775 			syncer_final_iter--;
1776 		/*
1777 		 * The variable rushjob allows the kernel to speed up the
1778 		 * processing of the filesystem syncer process. A rushjob
1779 		 * value of N tells the filesystem syncer to process the next
1780 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1781 		 * is used by the soft update code to speed up the filesystem
1782 		 * syncer process when the incore state is getting so far
1783 		 * ahead of the disk that the kernel memory pool is being
1784 		 * threatened with exhaustion.
1785 		 */
1786 		if (rushjob > 0) {
1787 			rushjob -= 1;
1788 			continue;
1789 		}
1790 		/*
1791 		 * Just sleep for a short period of time between
1792 		 * iterations when shutting down to allow some I/O
1793 		 * to happen.
1794 		 *
1795 		 * If it has taken us less than a second to process the
1796 		 * current work, then wait. Otherwise start right over
1797 		 * again. We can still lose time if any single round
1798 		 * takes more than two seconds, but it does not really
1799 		 * matter as we are just trying to generally pace the
1800 		 * filesystem activity.
1801 		 */
1802 		if (syncer_state != SYNCER_RUNNING)
1803 			msleep(&dummychan, &sync_mtx, PPAUSE, "syncfnl",
1804 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
1805 		else if (time_uptime == starttime)
1806 			msleep(&lbolt, &sync_mtx, PPAUSE, "syncer", 0);
1807 	}
1808 }
1809 
1810 /*
1811  * Request the syncer daemon to speed up its work.
1812  * We never push it to speed up more than half of its
1813  * normal turn time, otherwise it could take over the cpu.
1814  */
1815 int
1816 speedup_syncer(void)
1817 {
1818 	struct thread *td;
1819 	int ret = 0;
1820 
1821 	td = FIRST_THREAD_IN_PROC(updateproc);
1822 	mtx_lock(&sync_mtx);
1823 	if (rushjob < syncdelay / 2) {
1824 		rushjob += 1;
1825 		stat_rush_requests += 1;
1826 		ret = 1;
1827 	}
1828 	mtx_unlock(&sync_mtx);
1829 	sleepq_remove(td, &lbolt);
1830 	return (ret);
1831 }
1832 
1833 /*
1834  * Tell the syncer to speed up its work and run though its work
1835  * list several times, then tell it to shut down.
1836  */
1837 static void
1838 syncer_shutdown(void *arg, int howto)
1839 {
1840 	struct thread *td;
1841 
1842 	if (howto & RB_NOSYNC)
1843 		return;
1844 	td = FIRST_THREAD_IN_PROC(updateproc);
1845 	mtx_lock(&sync_mtx);
1846 	syncer_state = SYNCER_SHUTTING_DOWN;
1847 	rushjob = 0;
1848 	mtx_unlock(&sync_mtx);
1849 	sleepq_remove(td, &lbolt);
1850 	kproc_shutdown(arg, howto);
1851 }
1852 
1853 /*
1854  * Reassign a buffer from one vnode to another.
1855  * Used to assign file specific control information
1856  * (indirect blocks) to the vnode to which they belong.
1857  */
1858 void
1859 reassignbuf(struct buf *bp)
1860 {
1861 	struct vnode *vp;
1862 	struct bufobj *bo;
1863 	int delay;
1864 #ifdef INVARIANTS
1865 	struct bufv *bv;
1866 #endif
1867 
1868 	vp = bp->b_vp;
1869 	bo = bp->b_bufobj;
1870 	++reassignbufcalls;
1871 
1872 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1873 	    bp, bp->b_vp, bp->b_flags);
1874 	/*
1875 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1876 	 * is not fully linked in.
1877 	 */
1878 	if (bp->b_flags & B_PAGING)
1879 		panic("cannot reassign paging buffer");
1880 
1881 	/*
1882 	 * Delete from old vnode list, if on one.
1883 	 */
1884 	VI_LOCK(vp);
1885 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1886 		buf_vlist_remove(bp);
1887 	else
1888 		panic("reassignbuf: Buffer %p not on queue.", bp);
1889 	/*
1890 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1891 	 * of clean buffers.
1892 	 */
1893 	if (bp->b_flags & B_DELWRI) {
1894 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1895 			switch (vp->v_type) {
1896 			case VDIR:
1897 				delay = dirdelay;
1898 				break;
1899 			case VCHR:
1900 				delay = metadelay;
1901 				break;
1902 			default:
1903 				delay = filedelay;
1904 			}
1905 			vn_syncer_add_to_worklist(bo, delay);
1906 		}
1907 		buf_vlist_add(bp, bo, BX_VNDIRTY);
1908 	} else {
1909 		buf_vlist_add(bp, bo, BX_VNCLEAN);
1910 
1911 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1912 			mtx_lock(&sync_mtx);
1913 			LIST_REMOVE(bo, bo_synclist);
1914 			syncer_worklist_len--;
1915 			mtx_unlock(&sync_mtx);
1916 			bo->bo_flag &= ~BO_ONWORKLST;
1917 		}
1918 	}
1919 #ifdef INVARIANTS
1920 	bv = &bo->bo_clean;
1921 	bp = TAILQ_FIRST(&bv->bv_hd);
1922 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1923 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1924 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1925 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1926 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1927 	bv = &bo->bo_dirty;
1928 	bp = TAILQ_FIRST(&bv->bv_hd);
1929 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1930 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1931 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1932 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1933 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1934 #endif
1935 	VI_UNLOCK(vp);
1936 }
1937 
1938 /*
1939  * Increment the use and hold counts on the vnode, taking care to reference
1940  * the driver's usecount if this is a chardev.  The vholdl() will remove
1941  * the vnode from the free list if it is presently free.  Requires the
1942  * vnode interlock and returns with it held.
1943  */
1944 static void
1945 v_incr_usecount(struct vnode *vp)
1946 {
1947 
1948 	CTR3(KTR_VFS, "v_incr_usecount: vp %p holdcnt %d usecount %d\n",
1949 	    vp, vp->v_holdcnt, vp->v_usecount);
1950 	vp->v_usecount++;
1951 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1952 		dev_lock();
1953 		vp->v_rdev->si_usecount++;
1954 		dev_unlock();
1955 	}
1956 	vholdl(vp);
1957 }
1958 
1959 /*
1960  * Turn a holdcnt into a use+holdcnt such that only one call to
1961  * v_decr_usecount is needed.
1962  */
1963 static void
1964 v_upgrade_usecount(struct vnode *vp)
1965 {
1966 
1967 	CTR3(KTR_VFS, "v_upgrade_usecount: vp %p holdcnt %d usecount %d\n",
1968 	    vp, vp->v_holdcnt, vp->v_usecount);
1969 	vp->v_usecount++;
1970 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1971 		dev_lock();
1972 		vp->v_rdev->si_usecount++;
1973 		dev_unlock();
1974 	}
1975 }
1976 
1977 /*
1978  * Decrement the vnode use and hold count along with the driver's usecount
1979  * if this is a chardev.  The vdropl() below releases the vnode interlock
1980  * as it may free the vnode.
1981  */
1982 static void
1983 v_decr_usecount(struct vnode *vp)
1984 {
1985 
1986 	CTR3(KTR_VFS, "v_decr_usecount: 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_usecount: 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 	vdropl(vp);
1998 }
1999 
2000 /*
2001  * Decrement only the use count and driver use count.  This is intended to
2002  * be paired with a follow on vdropl() to release the remaining hold count.
2003  * In this way we may vgone() a vnode with a 0 usecount without risk of
2004  * having it end up on a free list because the hold count is kept above 0.
2005  */
2006 static void
2007 v_decr_useonly(struct vnode *vp)
2008 {
2009 
2010 	CTR3(KTR_VFS, "v_decr_useonly: vp %p holdcnt %d usecount %d\n",
2011 	    vp, vp->v_holdcnt, vp->v_usecount);
2012 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2013 	VNASSERT(vp->v_usecount > 0, vp,
2014 	    ("v_decr_useonly: negative usecount"));
2015 	vp->v_usecount--;
2016 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2017 		dev_lock();
2018 		vp->v_rdev->si_usecount--;
2019 		dev_unlock();
2020 	}
2021 }
2022 
2023 /*
2024  * Grab a particular vnode from the free list, increment its
2025  * reference count and lock it. The vnode lock bit is set if the
2026  * vnode is being eliminated in vgone. The process is awakened
2027  * when the transition is completed, and an error returned to
2028  * indicate that the vnode is no longer usable (possibly having
2029  * been changed to a new filesystem type).
2030  */
2031 int
2032 vget(struct vnode *vp, int flags, struct thread *td)
2033 {
2034 	int oweinact;
2035 	int oldflags;
2036 	int error;
2037 
2038 	error = 0;
2039 	oldflags = flags;
2040 	oweinact = 0;
2041 	VFS_ASSERT_GIANT(vp->v_mount);
2042 	if ((flags & LK_INTERLOCK) == 0)
2043 		VI_LOCK(vp);
2044 	/*
2045 	 * If the inactive call was deferred because vput() was called
2046 	 * with a shared lock, we have to do it here before another thread
2047 	 * gets a reference to data that should be dead.
2048 	 */
2049 	if (vp->v_iflag & VI_OWEINACT) {
2050 		if (flags & LK_NOWAIT) {
2051 			VI_UNLOCK(vp);
2052 			return (EBUSY);
2053 		}
2054 		flags &= ~LK_TYPE_MASK;
2055 		flags |= LK_EXCLUSIVE;
2056 		oweinact = 1;
2057 	}
2058 	vholdl(vp);
2059 	if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2060 		vdrop(vp);
2061 		return (error);
2062 	}
2063 	VI_LOCK(vp);
2064 	/* Upgrade our holdcnt to a usecount. */
2065 	v_upgrade_usecount(vp);
2066 	if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2067 		panic("vget: vn_lock failed to return ENOENT\n");
2068 	if (oweinact) {
2069 		if (vp->v_iflag & VI_OWEINACT)
2070 			vinactive(vp, td);
2071 		VI_UNLOCK(vp);
2072 		if ((oldflags & LK_TYPE_MASK) == 0)
2073 			VOP_UNLOCK(vp, 0);
2074 	} else
2075 		VI_UNLOCK(vp);
2076 	return (0);
2077 }
2078 
2079 /*
2080  * Increase the reference count of a vnode.
2081  */
2082 void
2083 vref(struct vnode *vp)
2084 {
2085 
2086 	VI_LOCK(vp);
2087 	v_incr_usecount(vp);
2088 	VI_UNLOCK(vp);
2089 }
2090 
2091 /*
2092  * Return reference count of a vnode.
2093  *
2094  * The results of this call are only guaranteed when some mechanism other
2095  * than the VI lock is used to stop other processes from gaining references
2096  * to the vnode.  This may be the case if the caller holds the only reference.
2097  * This is also useful when stale data is acceptable as race conditions may
2098  * be accounted for by some other means.
2099  */
2100 int
2101 vrefcnt(struct vnode *vp)
2102 {
2103 	int usecnt;
2104 
2105 	VI_LOCK(vp);
2106 	usecnt = vp->v_usecount;
2107 	VI_UNLOCK(vp);
2108 
2109 	return (usecnt);
2110 }
2111 
2112 
2113 /*
2114  * Vnode put/release.
2115  * If count drops to zero, call inactive routine and return to freelist.
2116  */
2117 void
2118 vrele(struct vnode *vp)
2119 {
2120 	struct thread *td = curthread;	/* XXX */
2121 
2122 	KASSERT(vp != NULL, ("vrele: null vp"));
2123 	VFS_ASSERT_GIANT(vp->v_mount);
2124 
2125 	VI_LOCK(vp);
2126 
2127 	/* Skip this v_writecount check if we're going to panic below. */
2128 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2129 	    ("vrele: missed vn_close"));
2130 
2131 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2132 	    vp->v_usecount == 1)) {
2133 		v_decr_usecount(vp);
2134 		return;
2135 	}
2136 	if (vp->v_usecount != 1) {
2137 #ifdef DIAGNOSTIC
2138 		vprint("vrele: negative ref count", vp);
2139 #endif
2140 		VI_UNLOCK(vp);
2141 		panic("vrele: negative ref cnt");
2142 	}
2143 	/*
2144 	 * We want to hold the vnode until the inactive finishes to
2145 	 * prevent vgone() races.  We drop the use count here and the
2146 	 * hold count below when we're done.
2147 	 */
2148 	v_decr_useonly(vp);
2149 	/*
2150 	 * We must call VOP_INACTIVE with the node locked. Mark
2151 	 * as VI_DOINGINACT to avoid recursion.
2152 	 */
2153 	vp->v_iflag |= VI_OWEINACT;
2154 	if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK) == 0) {
2155 		VI_LOCK(vp);
2156 		if (vp->v_usecount > 0)
2157 			vp->v_iflag &= ~VI_OWEINACT;
2158 		if (vp->v_iflag & VI_OWEINACT)
2159 			vinactive(vp, td);
2160 		VOP_UNLOCK(vp, 0);
2161 	} else {
2162 		VI_LOCK(vp);
2163 		if (vp->v_usecount > 0)
2164 			vp->v_iflag &= ~VI_OWEINACT;
2165 	}
2166 	vdropl(vp);
2167 }
2168 
2169 /*
2170  * Release an already locked vnode.  This give the same effects as
2171  * unlock+vrele(), but takes less time and avoids releasing and
2172  * re-aquiring the lock (as vrele() acquires the lock internally.)
2173  */
2174 void
2175 vput(struct vnode *vp)
2176 {
2177 	struct thread *td = curthread;	/* XXX */
2178 	int error;
2179 
2180 	KASSERT(vp != NULL, ("vput: null vp"));
2181 	ASSERT_VOP_LOCKED(vp, "vput");
2182 	VFS_ASSERT_GIANT(vp->v_mount);
2183 	VI_LOCK(vp);
2184 	/* Skip this v_writecount check if we're going to panic below. */
2185 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2186 	    ("vput: missed vn_close"));
2187 	error = 0;
2188 
2189 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2190 	    vp->v_usecount == 1)) {
2191 		VOP_UNLOCK(vp, 0);
2192 		v_decr_usecount(vp);
2193 		return;
2194 	}
2195 
2196 	if (vp->v_usecount != 1) {
2197 #ifdef DIAGNOSTIC
2198 		vprint("vput: negative ref count", vp);
2199 #endif
2200 		panic("vput: negative ref cnt");
2201 	}
2202 	/*
2203 	 * We want to hold the vnode until the inactive finishes to
2204 	 * prevent vgone() races.  We drop the use count here and the
2205 	 * hold count below when we're done.
2206 	 */
2207 	v_decr_useonly(vp);
2208 	vp->v_iflag |= VI_OWEINACT;
2209 	if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2210 		error = VOP_LOCK(vp, LK_UPGRADE|LK_INTERLOCK|LK_NOWAIT);
2211 		VI_LOCK(vp);
2212 		if (error) {
2213 			if (vp->v_usecount > 0)
2214 				vp->v_iflag &= ~VI_OWEINACT;
2215 			goto done;
2216 		}
2217 	}
2218 	if (vp->v_usecount > 0)
2219 		vp->v_iflag &= ~VI_OWEINACT;
2220 	if (vp->v_iflag & VI_OWEINACT)
2221 		vinactive(vp, td);
2222 	VOP_UNLOCK(vp, 0);
2223 done:
2224 	vdropl(vp);
2225 }
2226 
2227 /*
2228  * Somebody doesn't want the vnode recycled.
2229  */
2230 void
2231 vhold(struct vnode *vp)
2232 {
2233 
2234 	VI_LOCK(vp);
2235 	vholdl(vp);
2236 	VI_UNLOCK(vp);
2237 }
2238 
2239 void
2240 vholdl(struct vnode *vp)
2241 {
2242 
2243 	vp->v_holdcnt++;
2244 	if (VSHOULDBUSY(vp))
2245 		vbusy(vp);
2246 }
2247 
2248 /*
2249  * Note that there is one less who cares about this vnode.  vdrop() is the
2250  * opposite of vhold().
2251  */
2252 void
2253 vdrop(struct vnode *vp)
2254 {
2255 
2256 	VI_LOCK(vp);
2257 	vdropl(vp);
2258 }
2259 
2260 /*
2261  * Drop the hold count of the vnode.  If this is the last reference to
2262  * the vnode we will free it if it has been vgone'd otherwise it is
2263  * placed on the free list.
2264  */
2265 void
2266 vdropl(struct vnode *vp)
2267 {
2268 
2269 	ASSERT_VI_LOCKED(vp, "vdropl");
2270 	if (vp->v_holdcnt <= 0)
2271 		panic("vdrop: holdcnt %d", vp->v_holdcnt);
2272 	vp->v_holdcnt--;
2273 	if (vp->v_holdcnt == 0) {
2274 		if (vp->v_iflag & VI_DOOMED) {
2275 			vdestroy(vp);
2276 			return;
2277 		} else
2278 			vfree(vp);
2279 	}
2280 	VI_UNLOCK(vp);
2281 }
2282 
2283 /*
2284  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2285  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2286  * OWEINACT tracks whether a vnode missed a call to inactive due to a
2287  * failed lock upgrade.
2288  */
2289 static void
2290 vinactive(struct vnode *vp, struct thread *td)
2291 {
2292 
2293 	ASSERT_VOP_LOCKED(vp, "vinactive");
2294 	ASSERT_VI_LOCKED(vp, "vinactive");
2295 	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2296 	    ("vinactive: recursed on VI_DOINGINACT"));
2297 	vp->v_iflag |= VI_DOINGINACT;
2298 	vp->v_iflag &= ~VI_OWEINACT;
2299 	VI_UNLOCK(vp);
2300 	VOP_INACTIVE(vp, td);
2301 	VI_LOCK(vp);
2302 	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2303 	    ("vinactive: lost VI_DOINGINACT"));
2304 	vp->v_iflag &= ~VI_DOINGINACT;
2305 }
2306 
2307 /*
2308  * Remove any vnodes in the vnode table belonging to mount point mp.
2309  *
2310  * If FORCECLOSE is not specified, there should not be any active ones,
2311  * return error if any are found (nb: this is a user error, not a
2312  * system error). If FORCECLOSE is specified, detach any active vnodes
2313  * that are found.
2314  *
2315  * If WRITECLOSE is set, only flush out regular file vnodes open for
2316  * writing.
2317  *
2318  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2319  *
2320  * `rootrefs' specifies the base reference count for the root vnode
2321  * of this filesystem. The root vnode is considered busy if its
2322  * v_usecount exceeds this value. On a successful return, vflush(, td)
2323  * will call vrele() on the root vnode exactly rootrefs times.
2324  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2325  * be zero.
2326  */
2327 #ifdef DIAGNOSTIC
2328 static int busyprt = 0;		/* print out busy vnodes */
2329 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2330 #endif
2331 
2332 int
2333 vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
2334 {
2335 	struct vnode *vp, *mvp, *rootvp = NULL;
2336 	struct vattr vattr;
2337 	int busy = 0, error;
2338 
2339 	CTR1(KTR_VFS, "vflush: mp %p", mp);
2340 	if (rootrefs > 0) {
2341 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2342 		    ("vflush: bad args"));
2343 		/*
2344 		 * Get the filesystem root vnode. We can vput() it
2345 		 * immediately, since with rootrefs > 0, it won't go away.
2346 		 */
2347 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp, td)) != 0)
2348 			return (error);
2349 		vput(rootvp);
2350 
2351 	}
2352 	MNT_ILOCK(mp);
2353 loop:
2354 	MNT_VNODE_FOREACH(vp, mp, mvp) {
2355 
2356 		VI_LOCK(vp);
2357 		vholdl(vp);
2358 		MNT_IUNLOCK(mp);
2359 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2360 		if (error) {
2361 			vdrop(vp);
2362 			MNT_ILOCK(mp);
2363 			MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2364 			goto loop;
2365 		}
2366 		/*
2367 		 * Skip over a vnodes marked VV_SYSTEM.
2368 		 */
2369 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2370 			VOP_UNLOCK(vp, 0);
2371 			vdrop(vp);
2372 			MNT_ILOCK(mp);
2373 			continue;
2374 		}
2375 		/*
2376 		 * If WRITECLOSE is set, flush out unlinked but still open
2377 		 * files (even if open only for reading) and regular file
2378 		 * vnodes open for writing.
2379 		 */
2380 		if (flags & WRITECLOSE) {
2381 			error = VOP_GETATTR(vp, &vattr, td->td_ucred, td);
2382 			VI_LOCK(vp);
2383 
2384 			if ((vp->v_type == VNON ||
2385 			    (error == 0 && vattr.va_nlink > 0)) &&
2386 			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2387 				VOP_UNLOCK(vp, 0);
2388 				vdropl(vp);
2389 				MNT_ILOCK(mp);
2390 				continue;
2391 			}
2392 		} else
2393 			VI_LOCK(vp);
2394 		/*
2395 		 * With v_usecount == 0, all we need to do is clear out the
2396 		 * vnode data structures and we are done.
2397 		 *
2398 		 * If FORCECLOSE is set, forcibly close the vnode.
2399 		 */
2400 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2401 			VNASSERT(vp->v_usecount == 0 ||
2402 			    (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2403 			    ("device VNODE %p is FORCECLOSED", vp));
2404 			vgonel(vp);
2405 		} else {
2406 			busy++;
2407 #ifdef DIAGNOSTIC
2408 			if (busyprt)
2409 				vprint("vflush: busy vnode", vp);
2410 #endif
2411 		}
2412 		VOP_UNLOCK(vp, 0);
2413 		vdropl(vp);
2414 		MNT_ILOCK(mp);
2415 	}
2416 	MNT_IUNLOCK(mp);
2417 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2418 		/*
2419 		 * If just the root vnode is busy, and if its refcount
2420 		 * is equal to `rootrefs', then go ahead and kill it.
2421 		 */
2422 		VI_LOCK(rootvp);
2423 		KASSERT(busy > 0, ("vflush: not busy"));
2424 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2425 		    ("vflush: usecount %d < rootrefs %d",
2426 		     rootvp->v_usecount, rootrefs));
2427 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2428 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2429 			vgone(rootvp);
2430 			VOP_UNLOCK(rootvp, 0);
2431 			busy = 0;
2432 		} else
2433 			VI_UNLOCK(rootvp);
2434 	}
2435 	if (busy)
2436 		return (EBUSY);
2437 	for (; rootrefs > 0; rootrefs--)
2438 		vrele(rootvp);
2439 	return (0);
2440 }
2441 
2442 /*
2443  * Recycle an unused vnode to the front of the free list.
2444  */
2445 int
2446 vrecycle(struct vnode *vp, struct thread *td)
2447 {
2448 	int recycled;
2449 
2450 	ASSERT_VOP_LOCKED(vp, "vrecycle");
2451 	recycled = 0;
2452 	VI_LOCK(vp);
2453 	if (vp->v_usecount == 0) {
2454 		recycled = 1;
2455 		vgonel(vp);
2456 	}
2457 	VI_UNLOCK(vp);
2458 	return (recycled);
2459 }
2460 
2461 /*
2462  * Eliminate all activity associated with a vnode
2463  * in preparation for reuse.
2464  */
2465 void
2466 vgone(struct vnode *vp)
2467 {
2468 	VI_LOCK(vp);
2469 	vgonel(vp);
2470 	VI_UNLOCK(vp);
2471 }
2472 
2473 /*
2474  * vgone, with the vp interlock held.
2475  */
2476 void
2477 vgonel(struct vnode *vp)
2478 {
2479 	struct thread *td;
2480 	int oweinact;
2481 	int active;
2482 	struct mount *mp;
2483 
2484 	CTR1(KTR_VFS, "vgonel: vp %p", vp);
2485 	ASSERT_VOP_LOCKED(vp, "vgonel");
2486 	ASSERT_VI_LOCKED(vp, "vgonel");
2487 	VNASSERT(vp->v_holdcnt, vp,
2488 	    ("vgonel: vp %p has no reference.", vp));
2489 	td = curthread;
2490 
2491 	/*
2492 	 * Don't vgonel if we're already doomed.
2493 	 */
2494 	if (vp->v_iflag & VI_DOOMED)
2495 		return;
2496 	vp->v_iflag |= VI_DOOMED;
2497 	/*
2498 	 * Check to see if the vnode is in use.  If so, we have to call
2499 	 * VOP_CLOSE() and VOP_INACTIVE().
2500 	 */
2501 	active = vp->v_usecount;
2502 	oweinact = (vp->v_iflag & VI_OWEINACT);
2503 	VI_UNLOCK(vp);
2504 	/*
2505 	 * Clean out any buffers associated with the vnode.
2506 	 * If the flush fails, just toss the buffers.
2507 	 */
2508 	mp = NULL;
2509 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2510 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
2511 	if (vinvalbuf(vp, V_SAVE, td, 0, 0) != 0)
2512 		vinvalbuf(vp, 0, td, 0, 0);
2513 
2514 	/*
2515 	 * If purging an active vnode, it must be closed and
2516 	 * deactivated before being reclaimed.
2517 	 */
2518 	if (active)
2519 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2520 	if (oweinact || active) {
2521 		VI_LOCK(vp);
2522 		if ((vp->v_iflag & VI_DOINGINACT) == 0)
2523 			vinactive(vp, td);
2524 		VI_UNLOCK(vp);
2525 	}
2526 	/*
2527 	 * Reclaim the vnode.
2528 	 */
2529 	if (VOP_RECLAIM(vp, td))
2530 		panic("vgone: cannot reclaim");
2531 	if (mp != NULL)
2532 		vn_finished_secondary_write(mp);
2533 	VNASSERT(vp->v_object == NULL, vp,
2534 	    ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2535 	/*
2536 	 * Delete from old mount point vnode list.
2537 	 */
2538 	delmntque(vp);
2539 	cache_purge(vp);
2540 	/*
2541 	 * Done with purge, reset to the standard lock and invalidate
2542 	 * the vnode.
2543 	 */
2544 	VI_LOCK(vp);
2545 	vp->v_vnlock = &vp->v_lock;
2546 	vp->v_op = &dead_vnodeops;
2547 	vp->v_tag = "none";
2548 	vp->v_type = VBAD;
2549 }
2550 
2551 /*
2552  * Calculate the total number of references to a special device.
2553  */
2554 int
2555 vcount(struct vnode *vp)
2556 {
2557 	int count;
2558 
2559 	dev_lock();
2560 	count = vp->v_rdev->si_usecount;
2561 	dev_unlock();
2562 	return (count);
2563 }
2564 
2565 /*
2566  * Same as above, but using the struct cdev *as argument
2567  */
2568 int
2569 count_dev(struct cdev *dev)
2570 {
2571 	int count;
2572 
2573 	dev_lock();
2574 	count = dev->si_usecount;
2575 	dev_unlock();
2576 	return(count);
2577 }
2578 
2579 /*
2580  * Print out a description of a vnode.
2581  */
2582 static char *typename[] =
2583 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2584  "VMARKER"};
2585 
2586 void
2587 vn_printf(struct vnode *vp, const char *fmt, ...)
2588 {
2589 	va_list ap;
2590 	char buf[256], buf2[16];
2591 	u_long flags;
2592 
2593 	va_start(ap, fmt);
2594 	vprintf(fmt, ap);
2595 	va_end(ap);
2596 	printf("%p: ", (void *)vp);
2597 	printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2598 	printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2599 	    vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2600 	buf[0] = '\0';
2601 	buf[1] = '\0';
2602 	if (vp->v_vflag & VV_ROOT)
2603 		strlcat(buf, "|VV_ROOT", sizeof(buf));
2604 	if (vp->v_vflag & VV_ISTTY)
2605 		strlcat(buf, "|VV_ISTTY", sizeof(buf));
2606 	if (vp->v_vflag & VV_NOSYNC)
2607 		strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2608 	if (vp->v_vflag & VV_CACHEDLABEL)
2609 		strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2610 	if (vp->v_vflag & VV_TEXT)
2611 		strlcat(buf, "|VV_TEXT", sizeof(buf));
2612 	if (vp->v_vflag & VV_COPYONWRITE)
2613 		strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2614 	if (vp->v_vflag & VV_SYSTEM)
2615 		strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2616 	if (vp->v_vflag & VV_PROCDEP)
2617 		strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2618 	if (vp->v_vflag & VV_NOKNOTE)
2619 		strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2620 	if (vp->v_vflag & VV_DELETED)
2621 		strlcat(buf, "|VV_DELETED", sizeof(buf));
2622 	if (vp->v_vflag & VV_MD)
2623 		strlcat(buf, "|VV_MD", sizeof(buf));
2624 	flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
2625 	    VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2626 	    VV_NOKNOTE | VV_DELETED | VV_MD);
2627 	if (flags != 0) {
2628 		snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2629 		strlcat(buf, buf2, sizeof(buf));
2630 	}
2631 	if (vp->v_iflag & VI_MOUNT)
2632 		strlcat(buf, "|VI_MOUNT", sizeof(buf));
2633 	if (vp->v_iflag & VI_AGE)
2634 		strlcat(buf, "|VI_AGE", sizeof(buf));
2635 	if (vp->v_iflag & VI_DOOMED)
2636 		strlcat(buf, "|VI_DOOMED", sizeof(buf));
2637 	if (vp->v_iflag & VI_FREE)
2638 		strlcat(buf, "|VI_FREE", sizeof(buf));
2639 	if (vp->v_iflag & VI_OBJDIRTY)
2640 		strlcat(buf, "|VI_OBJDIRTY", sizeof(buf));
2641 	if (vp->v_iflag & VI_DOINGINACT)
2642 		strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2643 	if (vp->v_iflag & VI_OWEINACT)
2644 		strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2645 	flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2646 	    VI_OBJDIRTY | VI_DOINGINACT | VI_OWEINACT);
2647 	if (flags != 0) {
2648 		snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2649 		strlcat(buf, buf2, sizeof(buf));
2650 	}
2651 	printf("    flags (%s)\n", buf + 1);
2652 	if (mtx_owned(VI_MTX(vp)))
2653 		printf(" VI_LOCKed");
2654 	if (vp->v_object != NULL)
2655 		printf("    v_object %p ref %d pages %d\n",
2656 		    vp->v_object, vp->v_object->ref_count,
2657 		    vp->v_object->resident_page_count);
2658 	printf("    ");
2659 	lockmgr_printinfo(vp->v_vnlock);
2660 	printf("\n");
2661 	if (vp->v_data != NULL)
2662 		VOP_PRINT(vp);
2663 }
2664 
2665 #ifdef DDB
2666 /*
2667  * List all of the locked vnodes in the system.
2668  * Called when debugging the kernel.
2669  */
2670 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2671 {
2672 	struct mount *mp, *nmp;
2673 	struct vnode *vp;
2674 
2675 	/*
2676 	 * Note: because this is DDB, we can't obey the locking semantics
2677 	 * for these structures, which means we could catch an inconsistent
2678 	 * state and dereference a nasty pointer.  Not much to be done
2679 	 * about that.
2680 	 */
2681 	db_printf("Locked vnodes\n");
2682 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2683 		nmp = TAILQ_NEXT(mp, mnt_list);
2684 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2685 			if (vp->v_type != VMARKER &&
2686 			    VOP_ISLOCKED(vp))
2687 				vprint("", vp);
2688 		}
2689 		nmp = TAILQ_NEXT(mp, mnt_list);
2690 	}
2691 }
2692 
2693 /*
2694  * Show details about the given vnode.
2695  */
2696 DB_SHOW_COMMAND(vnode, db_show_vnode)
2697 {
2698 	struct vnode *vp;
2699 
2700 	if (!have_addr)
2701 		return;
2702 	vp = (struct vnode *)addr;
2703 	vn_printf(vp, "vnode ");
2704 }
2705 #endif	/* DDB */
2706 
2707 /*
2708  * Fill in a struct xvfsconf based on a struct vfsconf.
2709  */
2710 static void
2711 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2712 {
2713 
2714 	strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2715 	xvfsp->vfc_typenum = vfsp->vfc_typenum;
2716 	xvfsp->vfc_refcount = vfsp->vfc_refcount;
2717 	xvfsp->vfc_flags = vfsp->vfc_flags;
2718 	/*
2719 	 * These are unused in userland, we keep them
2720 	 * to not break binary compatibility.
2721 	 */
2722 	xvfsp->vfc_vfsops = NULL;
2723 	xvfsp->vfc_next = NULL;
2724 }
2725 
2726 /*
2727  * Top level filesystem related information gathering.
2728  */
2729 static int
2730 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2731 {
2732 	struct vfsconf *vfsp;
2733 	struct xvfsconf xvfsp;
2734 	int error;
2735 
2736 	error = 0;
2737 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2738 		bzero(&xvfsp, sizeof(xvfsp));
2739 		vfsconf2x(vfsp, &xvfsp);
2740 		error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
2741 		if (error)
2742 			break;
2743 	}
2744 	return (error);
2745 }
2746 
2747 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2748     "S,xvfsconf", "List of all configured filesystems");
2749 
2750 #ifndef BURN_BRIDGES
2751 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2752 
2753 static int
2754 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2755 {
2756 	int *name = (int *)arg1 - 1;	/* XXX */
2757 	u_int namelen = arg2 + 1;	/* XXX */
2758 	struct vfsconf *vfsp;
2759 	struct xvfsconf xvfsp;
2760 
2761 	printf("WARNING: userland calling deprecated sysctl, "
2762 	    "please rebuild world\n");
2763 
2764 #if 1 || defined(COMPAT_PRELITE2)
2765 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2766 	if (namelen == 1)
2767 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2768 #endif
2769 
2770 	switch (name[1]) {
2771 	case VFS_MAXTYPENUM:
2772 		if (namelen != 2)
2773 			return (ENOTDIR);
2774 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2775 	case VFS_CONF:
2776 		if (namelen != 3)
2777 			return (ENOTDIR);	/* overloaded */
2778 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
2779 			if (vfsp->vfc_typenum == name[2])
2780 				break;
2781 		if (vfsp == NULL)
2782 			return (EOPNOTSUPP);
2783 		bzero(&xvfsp, sizeof(xvfsp));
2784 		vfsconf2x(vfsp, &xvfsp);
2785 		return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
2786 	}
2787 	return (EOPNOTSUPP);
2788 }
2789 
2790 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
2791 	vfs_sysctl, "Generic filesystem");
2792 
2793 #if 1 || defined(COMPAT_PRELITE2)
2794 
2795 static int
2796 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2797 {
2798 	int error;
2799 	struct vfsconf *vfsp;
2800 	struct ovfsconf ovfs;
2801 
2802 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2803 		bzero(&ovfs, sizeof(ovfs));
2804 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2805 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2806 		ovfs.vfc_index = vfsp->vfc_typenum;
2807 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2808 		ovfs.vfc_flags = vfsp->vfc_flags;
2809 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2810 		if (error)
2811 			return error;
2812 	}
2813 	return 0;
2814 }
2815 
2816 #endif /* 1 || COMPAT_PRELITE2 */
2817 #endif /* !BURN_BRIDGES */
2818 
2819 #define KINFO_VNODESLOP		10
2820 #ifdef notyet
2821 /*
2822  * Dump vnode list (via sysctl).
2823  */
2824 /* ARGSUSED */
2825 static int
2826 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2827 {
2828 	struct xvnode *xvn;
2829 	struct thread *td = req->td;
2830 	struct mount *mp;
2831 	struct vnode *vp;
2832 	int error, len, n;
2833 
2834 	/*
2835 	 * Stale numvnodes access is not fatal here.
2836 	 */
2837 	req->lock = 0;
2838 	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
2839 	if (!req->oldptr)
2840 		/* Make an estimate */
2841 		return (SYSCTL_OUT(req, 0, len));
2842 
2843 	error = sysctl_wire_old_buffer(req, 0);
2844 	if (error != 0)
2845 		return (error);
2846 	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
2847 	n = 0;
2848 	mtx_lock(&mountlist_mtx);
2849 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2850 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
2851 			continue;
2852 		MNT_ILOCK(mp);
2853 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2854 			if (n == len)
2855 				break;
2856 			vref(vp);
2857 			xvn[n].xv_size = sizeof *xvn;
2858 			xvn[n].xv_vnode = vp;
2859 			xvn[n].xv_id = 0;	/* XXX compat */
2860 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
2861 			XV_COPY(usecount);
2862 			XV_COPY(writecount);
2863 			XV_COPY(holdcnt);
2864 			XV_COPY(mount);
2865 			XV_COPY(numoutput);
2866 			XV_COPY(type);
2867 #undef XV_COPY
2868 			xvn[n].xv_flag = vp->v_vflag;
2869 
2870 			switch (vp->v_type) {
2871 			case VREG:
2872 			case VDIR:
2873 			case VLNK:
2874 				break;
2875 			case VBLK:
2876 			case VCHR:
2877 				if (vp->v_rdev == NULL) {
2878 					vrele(vp);
2879 					continue;
2880 				}
2881 				xvn[n].xv_dev = dev2udev(vp->v_rdev);
2882 				break;
2883 			case VSOCK:
2884 				xvn[n].xv_socket = vp->v_socket;
2885 				break;
2886 			case VFIFO:
2887 				xvn[n].xv_fifo = vp->v_fifoinfo;
2888 				break;
2889 			case VNON:
2890 			case VBAD:
2891 			default:
2892 				/* shouldn't happen? */
2893 				vrele(vp);
2894 				continue;
2895 			}
2896 			vrele(vp);
2897 			++n;
2898 		}
2899 		MNT_IUNLOCK(mp);
2900 		mtx_lock(&mountlist_mtx);
2901 		vfs_unbusy(mp, td);
2902 		if (n == len)
2903 			break;
2904 	}
2905 	mtx_unlock(&mountlist_mtx);
2906 
2907 	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
2908 	free(xvn, M_TEMP);
2909 	return (error);
2910 }
2911 
2912 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2913 	0, 0, sysctl_vnode, "S,xvnode", "");
2914 #endif
2915 
2916 /*
2917  * Unmount all filesystems. The list is traversed in reverse order
2918  * of mounting to avoid dependencies.
2919  */
2920 void
2921 vfs_unmountall(void)
2922 {
2923 	struct mount *mp;
2924 	struct thread *td;
2925 	int error;
2926 
2927 	KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
2928 	td = curthread;
2929 	/*
2930 	 * Since this only runs when rebooting, it is not interlocked.
2931 	 */
2932 	while(!TAILQ_EMPTY(&mountlist)) {
2933 		mp = TAILQ_LAST(&mountlist, mntlist);
2934 		error = dounmount(mp, MNT_FORCE, td);
2935 		if (error) {
2936 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
2937 			/*
2938 			 * XXX: Due to the way in which we mount the root
2939 			 * file system off of devfs, devfs will generate a
2940 			 * "busy" warning when we try to unmount it before
2941 			 * the root.  Don't print a warning as a result in
2942 			 * order to avoid false positive errors that may
2943 			 * cause needless upset.
2944 			 */
2945 			if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
2946 				printf("unmount of %s failed (",
2947 				    mp->mnt_stat.f_mntonname);
2948 				if (error == EBUSY)
2949 					printf("BUSY)\n");
2950 				else
2951 					printf("%d)\n", error);
2952 			}
2953 		} else {
2954 			/* The unmount has removed mp from the mountlist */
2955 		}
2956 	}
2957 }
2958 
2959 /*
2960  * perform msync on all vnodes under a mount point
2961  * the mount point must be locked.
2962  */
2963 void
2964 vfs_msync(struct mount *mp, int flags)
2965 {
2966 	struct vnode *vp, *mvp;
2967 	struct vm_object *obj;
2968 
2969 	MNT_ILOCK(mp);
2970 	MNT_VNODE_FOREACH(vp, mp, mvp) {
2971 		VI_LOCK(vp);
2972 		if ((vp->v_iflag & VI_OBJDIRTY) &&
2973 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
2974 			MNT_IUNLOCK(mp);
2975 			if (!vget(vp,
2976 			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
2977 			    curthread)) {
2978 				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
2979 					vput(vp);
2980 					MNT_ILOCK(mp);
2981 					continue;
2982 				}
2983 
2984 				obj = vp->v_object;
2985 				if (obj != NULL) {
2986 					VM_OBJECT_LOCK(obj);
2987 					vm_object_page_clean(obj, 0, 0,
2988 					    flags == MNT_WAIT ?
2989 					    OBJPC_SYNC : OBJPC_NOSYNC);
2990 					VM_OBJECT_UNLOCK(obj);
2991 				}
2992 				vput(vp);
2993 			}
2994 			MNT_ILOCK(mp);
2995 		} else
2996 			VI_UNLOCK(vp);
2997 	}
2998 	MNT_IUNLOCK(mp);
2999 }
3000 
3001 /*
3002  * Mark a vnode as free, putting it up for recycling.
3003  */
3004 static void
3005 vfree(struct vnode *vp)
3006 {
3007 
3008 	CTR1(KTR_VFS, "vfree vp %p", vp);
3009 	ASSERT_VI_LOCKED(vp, "vfree");
3010 	mtx_lock(&vnode_free_list_mtx);
3011 	VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
3012 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
3013 	VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
3014 	VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
3015 	    ("vfree: Freeing doomed vnode"));
3016 	if (vp->v_iflag & VI_AGE) {
3017 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
3018 	} else {
3019 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
3020 	}
3021 	freevnodes++;
3022 	vp->v_iflag &= ~VI_AGE;
3023 	vp->v_iflag |= VI_FREE;
3024 	mtx_unlock(&vnode_free_list_mtx);
3025 }
3026 
3027 /*
3028  * Opposite of vfree() - mark a vnode as in use.
3029  */
3030 static void
3031 vbusy(struct vnode *vp)
3032 {
3033 	CTR1(KTR_VFS, "vbusy vp %p", vp);
3034 	ASSERT_VI_LOCKED(vp, "vbusy");
3035 	VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
3036 	VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
3037 
3038 	mtx_lock(&vnode_free_list_mtx);
3039 	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
3040 	freevnodes--;
3041 	vp->v_iflag &= ~(VI_FREE|VI_AGE);
3042 	mtx_unlock(&vnode_free_list_mtx);
3043 }
3044 
3045 /*
3046  * Initalize per-vnode helper structure to hold poll-related state.
3047  */
3048 void
3049 v_addpollinfo(struct vnode *vp)
3050 {
3051 	struct vpollinfo *vi;
3052 
3053 	vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3054 	if (vp->v_pollinfo != NULL) {
3055 		uma_zfree(vnodepoll_zone, vi);
3056 		return;
3057 	}
3058 	vp->v_pollinfo = vi;
3059 	mtx_init(&vp->v_pollinfo->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3060 	knlist_init(&vp->v_pollinfo->vpi_selinfo.si_note, vp, vfs_knllock,
3061 	    vfs_knlunlock, vfs_knllocked);
3062 }
3063 
3064 /*
3065  * Record a process's interest in events which might happen to
3066  * a vnode.  Because poll uses the historic select-style interface
3067  * internally, this routine serves as both the ``check for any
3068  * pending events'' and the ``record my interest in future events''
3069  * functions.  (These are done together, while the lock is held,
3070  * to avoid race conditions.)
3071  */
3072 int
3073 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3074 {
3075 
3076 	if (vp->v_pollinfo == NULL)
3077 		v_addpollinfo(vp);
3078 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3079 	if (vp->v_pollinfo->vpi_revents & events) {
3080 		/*
3081 		 * This leaves events we are not interested
3082 		 * in available for the other process which
3083 		 * which presumably had requested them
3084 		 * (otherwise they would never have been
3085 		 * recorded).
3086 		 */
3087 		events &= vp->v_pollinfo->vpi_revents;
3088 		vp->v_pollinfo->vpi_revents &= ~events;
3089 
3090 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3091 		return events;
3092 	}
3093 	vp->v_pollinfo->vpi_events |= events;
3094 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3095 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3096 	return 0;
3097 }
3098 
3099 /*
3100  * Routine to create and manage a filesystem syncer vnode.
3101  */
3102 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3103 static int	sync_fsync(struct  vop_fsync_args *);
3104 static int	sync_inactive(struct  vop_inactive_args *);
3105 static int	sync_reclaim(struct  vop_reclaim_args *);
3106 
3107 static struct vop_vector sync_vnodeops = {
3108 	.vop_bypass =	VOP_EOPNOTSUPP,
3109 	.vop_close =	sync_close,		/* close */
3110 	.vop_fsync =	sync_fsync,		/* fsync */
3111 	.vop_inactive =	sync_inactive,	/* inactive */
3112 	.vop_reclaim =	sync_reclaim,	/* reclaim */
3113 	.vop_lock1 =	vop_stdlock,	/* lock */
3114 	.vop_unlock =	vop_stdunlock,	/* unlock */
3115 	.vop_islocked =	vop_stdislocked,	/* islocked */
3116 };
3117 
3118 /*
3119  * Create a new filesystem syncer vnode for the specified mount point.
3120  */
3121 int
3122 vfs_allocate_syncvnode(struct mount *mp)
3123 {
3124 	struct vnode *vp;
3125 	static long start, incr, next;
3126 	int error;
3127 
3128 	/* Allocate a new vnode */
3129 	if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
3130 		mp->mnt_syncer = NULL;
3131 		return (error);
3132 	}
3133 	vp->v_type = VNON;
3134 	error = insmntque(vp, mp);
3135 	if (error != 0)
3136 		panic("vfs_allocate_syncvnode: insmntque failed");
3137 	/*
3138 	 * Place the vnode onto the syncer worklist. We attempt to
3139 	 * scatter them about on the list so that they will go off
3140 	 * at evenly distributed times even if all the filesystems
3141 	 * are mounted at once.
3142 	 */
3143 	next += incr;
3144 	if (next == 0 || next > syncer_maxdelay) {
3145 		start /= 2;
3146 		incr /= 2;
3147 		if (start == 0) {
3148 			start = syncer_maxdelay / 2;
3149 			incr = syncer_maxdelay;
3150 		}
3151 		next = start;
3152 	}
3153 	VI_LOCK(vp);
3154 	vn_syncer_add_to_worklist(&vp->v_bufobj,
3155 	    syncdelay > 0 ? next % syncdelay : 0);
3156 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3157 	mtx_lock(&sync_mtx);
3158 	sync_vnode_count++;
3159 	mtx_unlock(&sync_mtx);
3160 	VI_UNLOCK(vp);
3161 	mp->mnt_syncer = vp;
3162 	return (0);
3163 }
3164 
3165 /*
3166  * Do a lazy sync of the filesystem.
3167  */
3168 static int
3169 sync_fsync(struct vop_fsync_args *ap)
3170 {
3171 	struct vnode *syncvp = ap->a_vp;
3172 	struct mount *mp = syncvp->v_mount;
3173 	struct thread *td = ap->a_td;
3174 	int error;
3175 	struct bufobj *bo;
3176 
3177 	/*
3178 	 * We only need to do something if this is a lazy evaluation.
3179 	 */
3180 	if (ap->a_waitfor != MNT_LAZY)
3181 		return (0);
3182 
3183 	/*
3184 	 * Move ourselves to the back of the sync list.
3185 	 */
3186 	bo = &syncvp->v_bufobj;
3187 	BO_LOCK(bo);
3188 	vn_syncer_add_to_worklist(bo, syncdelay);
3189 	BO_UNLOCK(bo);
3190 
3191 	/*
3192 	 * Walk the list of vnodes pushing all that are dirty and
3193 	 * not already on the sync list.
3194 	 */
3195 	mtx_lock(&mountlist_mtx);
3196 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
3197 		mtx_unlock(&mountlist_mtx);
3198 		return (0);
3199 	}
3200 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3201 		vfs_unbusy(mp, td);
3202 		return (0);
3203 	}
3204 	MNT_ILOCK(mp);
3205 	mp->mnt_noasync++;
3206 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
3207 	MNT_IUNLOCK(mp);
3208 	vfs_msync(mp, MNT_NOWAIT);
3209 	error = VFS_SYNC(mp, MNT_LAZY, td);
3210 	MNT_ILOCK(mp);
3211 	mp->mnt_noasync--;
3212 	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3213 		mp->mnt_kern_flag |= MNTK_ASYNC;
3214 	MNT_IUNLOCK(mp);
3215 	vn_finished_write(mp);
3216 	vfs_unbusy(mp, td);
3217 	return (error);
3218 }
3219 
3220 /*
3221  * The syncer vnode is no referenced.
3222  */
3223 static int
3224 sync_inactive(struct vop_inactive_args *ap)
3225 {
3226 
3227 	vgone(ap->a_vp);
3228 	return (0);
3229 }
3230 
3231 /*
3232  * The syncer vnode is no longer needed and is being decommissioned.
3233  *
3234  * Modifications to the worklist must be protected by sync_mtx.
3235  */
3236 static int
3237 sync_reclaim(struct vop_reclaim_args *ap)
3238 {
3239 	struct vnode *vp = ap->a_vp;
3240 	struct bufobj *bo;
3241 
3242 	VI_LOCK(vp);
3243 	bo = &vp->v_bufobj;
3244 	vp->v_mount->mnt_syncer = NULL;
3245 	if (bo->bo_flag & BO_ONWORKLST) {
3246 		mtx_lock(&sync_mtx);
3247 		LIST_REMOVE(bo, bo_synclist);
3248 		syncer_worklist_len--;
3249 		sync_vnode_count--;
3250 		mtx_unlock(&sync_mtx);
3251 		bo->bo_flag &= ~BO_ONWORKLST;
3252 	}
3253 	VI_UNLOCK(vp);
3254 
3255 	return (0);
3256 }
3257 
3258 /*
3259  * Check if vnode represents a disk device
3260  */
3261 int
3262 vn_isdisk(struct vnode *vp, int *errp)
3263 {
3264 	int error;
3265 
3266 	error = 0;
3267 	dev_lock();
3268 	if (vp->v_type != VCHR)
3269 		error = ENOTBLK;
3270 	else if (vp->v_rdev == NULL)
3271 		error = ENXIO;
3272 	else if (vp->v_rdev->si_devsw == NULL)
3273 		error = ENXIO;
3274 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3275 		error = ENOTBLK;
3276 	dev_unlock();
3277 	if (errp != NULL)
3278 		*errp = error;
3279 	return (error == 0);
3280 }
3281 
3282 /*
3283  * Common filesystem object access control check routine.  Accepts a
3284  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3285  * and optional call-by-reference privused argument allowing vaccess()
3286  * to indicate to the caller whether privilege was used to satisfy the
3287  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3288  *
3289  * The ifdef'd CAPABILITIES version is here for reference, but is not
3290  * actually used.
3291  */
3292 int
3293 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3294     mode_t acc_mode, struct ucred *cred, int *privused)
3295 {
3296 	mode_t dac_granted;
3297 	mode_t priv_granted;
3298 
3299 	/*
3300 	 * Look for a normal, non-privileged way to access the file/directory
3301 	 * as requested.  If it exists, go with that.
3302 	 */
3303 
3304 	if (privused != NULL)
3305 		*privused = 0;
3306 
3307 	dac_granted = 0;
3308 
3309 	/* Check the owner. */
3310 	if (cred->cr_uid == file_uid) {
3311 		dac_granted |= VADMIN;
3312 		if (file_mode & S_IXUSR)
3313 			dac_granted |= VEXEC;
3314 		if (file_mode & S_IRUSR)
3315 			dac_granted |= VREAD;
3316 		if (file_mode & S_IWUSR)
3317 			dac_granted |= (VWRITE | VAPPEND);
3318 
3319 		if ((acc_mode & dac_granted) == acc_mode)
3320 			return (0);
3321 
3322 		goto privcheck;
3323 	}
3324 
3325 	/* Otherwise, check the groups (first match) */
3326 	if (groupmember(file_gid, cred)) {
3327 		if (file_mode & S_IXGRP)
3328 			dac_granted |= VEXEC;
3329 		if (file_mode & S_IRGRP)
3330 			dac_granted |= VREAD;
3331 		if (file_mode & S_IWGRP)
3332 			dac_granted |= (VWRITE | VAPPEND);
3333 
3334 		if ((acc_mode & dac_granted) == acc_mode)
3335 			return (0);
3336 
3337 		goto privcheck;
3338 	}
3339 
3340 	/* Otherwise, check everyone else. */
3341 	if (file_mode & S_IXOTH)
3342 		dac_granted |= VEXEC;
3343 	if (file_mode & S_IROTH)
3344 		dac_granted |= VREAD;
3345 	if (file_mode & S_IWOTH)
3346 		dac_granted |= (VWRITE | VAPPEND);
3347 	if ((acc_mode & dac_granted) == acc_mode)
3348 		return (0);
3349 
3350 privcheck:
3351 	/*
3352 	 * Build a privilege mask to determine if the set of privileges
3353 	 * satisfies the requirements when combined with the granted mask
3354 	 * from above.  For each privilege, if the privilege is required,
3355 	 * bitwise or the request type onto the priv_granted mask.
3356 	 */
3357 	priv_granted = 0;
3358 
3359 	if (type == VDIR) {
3360 		/*
3361 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3362 		 * requests, instead of PRIV_VFS_EXEC.
3363 		 */
3364 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3365 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3366 			priv_granted |= VEXEC;
3367 	} else {
3368 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3369 		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3370 			priv_granted |= VEXEC;
3371 	}
3372 
3373 	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3374 	    !priv_check_cred(cred, PRIV_VFS_READ, 0))
3375 		priv_granted |= VREAD;
3376 
3377 	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3378 	    !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3379 		priv_granted |= (VWRITE | VAPPEND);
3380 
3381 	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3382 	    !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3383 		priv_granted |= VADMIN;
3384 
3385 	if ((acc_mode & (priv_granted | dac_granted)) == acc_mode) {
3386 		/* XXX audit: privilege used */
3387 		if (privused != NULL)
3388 			*privused = 1;
3389 		return (0);
3390 	}
3391 
3392 	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3393 }
3394 
3395 /*
3396  * Credential check based on process requesting service, and per-attribute
3397  * permissions.
3398  */
3399 int
3400 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3401     struct thread *td, int access)
3402 {
3403 
3404 	/*
3405 	 * Kernel-invoked always succeeds.
3406 	 */
3407 	if (cred == NOCRED)
3408 		return (0);
3409 
3410 	/*
3411 	 * Do not allow privileged processes in jail to directly manipulate
3412 	 * system attributes.
3413 	 */
3414 	switch (attrnamespace) {
3415 	case EXTATTR_NAMESPACE_SYSTEM:
3416 		/* Potentially should be: return (EPERM); */
3417 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3418 	case EXTATTR_NAMESPACE_USER:
3419 		return (VOP_ACCESS(vp, access, cred, td));
3420 	default:
3421 		return (EPERM);
3422 	}
3423 }
3424 
3425 #ifdef DEBUG_VFS_LOCKS
3426 /*
3427  * This only exists to supress warnings from unlocked specfs accesses.  It is
3428  * no longer ok to have an unlocked VFS.
3429  */
3430 #define	IGNORE_LOCK(vp) ((vp)->v_type == VCHR || (vp)->v_type == VBAD)
3431 
3432 int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
3433 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
3434 
3435 int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
3436 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
3437 
3438 int vfs_badlock_print = 1;	/* Print lock violations. */
3439 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
3440 
3441 #ifdef KDB
3442 int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
3443 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
3444 #endif
3445 
3446 static void
3447 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3448 {
3449 
3450 #ifdef KDB
3451 	if (vfs_badlock_backtrace)
3452 		kdb_backtrace();
3453 #endif
3454 	if (vfs_badlock_print)
3455 		printf("%s: %p %s\n", str, (void *)vp, msg);
3456 	if (vfs_badlock_ddb)
3457 		kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3458 }
3459 
3460 void
3461 assert_vi_locked(struct vnode *vp, const char *str)
3462 {
3463 
3464 	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3465 		vfs_badlock("interlock is not locked but should be", str, vp);
3466 }
3467 
3468 void
3469 assert_vi_unlocked(struct vnode *vp, const char *str)
3470 {
3471 
3472 	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3473 		vfs_badlock("interlock is locked but should not be", str, vp);
3474 }
3475 
3476 void
3477 assert_vop_locked(struct vnode *vp, const char *str)
3478 {
3479 
3480 	if (vp && !IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == 0)
3481 		vfs_badlock("is not locked but should be", str, vp);
3482 }
3483 
3484 void
3485 assert_vop_unlocked(struct vnode *vp, const char *str)
3486 {
3487 
3488 	if (vp && !IGNORE_LOCK(vp) &&
3489 	    VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3490 		vfs_badlock("is locked but should not be", str, vp);
3491 }
3492 
3493 void
3494 assert_vop_elocked(struct vnode *vp, const char *str)
3495 {
3496 
3497 	if (vp && !IGNORE_LOCK(vp) &&
3498 	    VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3499 		vfs_badlock("is not exclusive locked but should be", str, vp);
3500 }
3501 
3502 #if 0
3503 void
3504 assert_vop_elocked_other(struct vnode *vp, const char *str)
3505 {
3506 
3507 	if (vp && !IGNORE_LOCK(vp) &&
3508 	    VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3509 		vfs_badlock("is not exclusive locked by another thread",
3510 		    str, vp);
3511 }
3512 
3513 void
3514 assert_vop_slocked(struct vnode *vp, const char *str)
3515 {
3516 
3517 	if (vp && !IGNORE_LOCK(vp) &&
3518 	    VOP_ISLOCKED(vp) != LK_SHARED)
3519 		vfs_badlock("is not locked shared but should be", str, vp);
3520 }
3521 #endif /* 0 */
3522 #endif /* DEBUG_VFS_LOCKS */
3523 
3524 void
3525 vop_rename_pre(void *ap)
3526 {
3527 	struct vop_rename_args *a = ap;
3528 
3529 #ifdef DEBUG_VFS_LOCKS
3530 	if (a->a_tvp)
3531 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3532 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3533 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3534 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3535 
3536 	/* Check the source (from). */
3537 	if (a->a_tdvp != a->a_fdvp && a->a_tvp != a->a_fdvp)
3538 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3539 	if (a->a_tvp != a->a_fvp)
3540 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3541 
3542 	/* Check the target. */
3543 	if (a->a_tvp)
3544 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3545 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3546 #endif
3547 	if (a->a_tdvp != a->a_fdvp)
3548 		vhold(a->a_fdvp);
3549 	if (a->a_tvp != a->a_fvp)
3550 		vhold(a->a_fvp);
3551 	vhold(a->a_tdvp);
3552 	if (a->a_tvp)
3553 		vhold(a->a_tvp);
3554 }
3555 
3556 void
3557 vop_strategy_pre(void *ap)
3558 {
3559 #ifdef DEBUG_VFS_LOCKS
3560 	struct vop_strategy_args *a;
3561 	struct buf *bp;
3562 
3563 	a = ap;
3564 	bp = a->a_bp;
3565 
3566 	/*
3567 	 * Cluster ops lock their component buffers but not the IO container.
3568 	 */
3569 	if ((bp->b_flags & B_CLUSTER) != 0)
3570 		return;
3571 
3572 	if (!BUF_ISLOCKED(bp)) {
3573 		if (vfs_badlock_print)
3574 			printf(
3575 			    "VOP_STRATEGY: bp is not locked but should be\n");
3576 		if (vfs_badlock_ddb)
3577 			kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3578 	}
3579 #endif
3580 }
3581 
3582 void
3583 vop_lookup_pre(void *ap)
3584 {
3585 #ifdef DEBUG_VFS_LOCKS
3586 	struct vop_lookup_args *a;
3587 	struct vnode *dvp;
3588 
3589 	a = ap;
3590 	dvp = a->a_dvp;
3591 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3592 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3593 #endif
3594 }
3595 
3596 void
3597 vop_lookup_post(void *ap, int rc)
3598 {
3599 #ifdef DEBUG_VFS_LOCKS
3600 	struct vop_lookup_args *a;
3601 	struct vnode *dvp;
3602 	struct vnode *vp;
3603 
3604 	a = ap;
3605 	dvp = a->a_dvp;
3606 	vp = *(a->a_vpp);
3607 
3608 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3609 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3610 
3611 	if (!rc)
3612 		ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3613 #endif
3614 }
3615 
3616 void
3617 vop_lock_pre(void *ap)
3618 {
3619 #ifdef DEBUG_VFS_LOCKS
3620 	struct vop_lock1_args *a = ap;
3621 
3622 	if ((a->a_flags & LK_INTERLOCK) == 0)
3623 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3624 	else
3625 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3626 #endif
3627 }
3628 
3629 void
3630 vop_lock_post(void *ap, int rc)
3631 {
3632 #ifdef DEBUG_VFS_LOCKS
3633 	struct vop_lock1_args *a = ap;
3634 
3635 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3636 	if (rc == 0)
3637 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
3638 #endif
3639 }
3640 
3641 void
3642 vop_unlock_pre(void *ap)
3643 {
3644 #ifdef DEBUG_VFS_LOCKS
3645 	struct vop_unlock_args *a = ap;
3646 
3647 	if (a->a_flags & LK_INTERLOCK)
3648 		ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
3649 	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
3650 #endif
3651 }
3652 
3653 void
3654 vop_unlock_post(void *ap, int rc)
3655 {
3656 #ifdef DEBUG_VFS_LOCKS
3657 	struct vop_unlock_args *a = ap;
3658 
3659 	if (a->a_flags & LK_INTERLOCK)
3660 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
3661 #endif
3662 }
3663 
3664 void
3665 vop_create_post(void *ap, int rc)
3666 {
3667 	struct vop_create_args *a = ap;
3668 
3669 	if (!rc)
3670 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3671 }
3672 
3673 void
3674 vop_link_post(void *ap, int rc)
3675 {
3676 	struct vop_link_args *a = ap;
3677 
3678 	if (!rc) {
3679 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
3680 		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
3681 	}
3682 }
3683 
3684 void
3685 vop_mkdir_post(void *ap, int rc)
3686 {
3687 	struct vop_mkdir_args *a = ap;
3688 
3689 	if (!rc)
3690 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3691 }
3692 
3693 void
3694 vop_mknod_post(void *ap, int rc)
3695 {
3696 	struct vop_mknod_args *a = ap;
3697 
3698 	if (!rc)
3699 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3700 }
3701 
3702 void
3703 vop_remove_post(void *ap, int rc)
3704 {
3705 	struct vop_remove_args *a = ap;
3706 
3707 	if (!rc) {
3708 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3709 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3710 	}
3711 }
3712 
3713 void
3714 vop_rename_post(void *ap, int rc)
3715 {
3716 	struct vop_rename_args *a = ap;
3717 
3718 	if (!rc) {
3719 		VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
3720 		VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
3721 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
3722 		if (a->a_tvp)
3723 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
3724 	}
3725 	if (a->a_tdvp != a->a_fdvp)
3726 		vdrop(a->a_fdvp);
3727 	if (a->a_tvp != a->a_fvp)
3728 		vdrop(a->a_fvp);
3729 	vdrop(a->a_tdvp);
3730 	if (a->a_tvp)
3731 		vdrop(a->a_tvp);
3732 }
3733 
3734 void
3735 vop_rmdir_post(void *ap, int rc)
3736 {
3737 	struct vop_rmdir_args *a = ap;
3738 
3739 	if (!rc) {
3740 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3741 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3742 	}
3743 }
3744 
3745 void
3746 vop_setattr_post(void *ap, int rc)
3747 {
3748 	struct vop_setattr_args *a = ap;
3749 
3750 	if (!rc)
3751 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
3752 }
3753 
3754 void
3755 vop_symlink_post(void *ap, int rc)
3756 {
3757 	struct vop_symlink_args *a = ap;
3758 
3759 	if (!rc)
3760 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3761 }
3762 
3763 static struct knlist fs_knlist;
3764 
3765 static void
3766 vfs_event_init(void *arg)
3767 {
3768 	knlist_init(&fs_knlist, NULL, NULL, NULL, NULL);
3769 }
3770 /* XXX - correct order? */
3771 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
3772 
3773 void
3774 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
3775 {
3776 
3777 	KNOTE_UNLOCKED(&fs_knlist, event);
3778 }
3779 
3780 static int	filt_fsattach(struct knote *kn);
3781 static void	filt_fsdetach(struct knote *kn);
3782 static int	filt_fsevent(struct knote *kn, long hint);
3783 
3784 struct filterops fs_filtops =
3785 	{ 0, filt_fsattach, filt_fsdetach, filt_fsevent };
3786 
3787 static int
3788 filt_fsattach(struct knote *kn)
3789 {
3790 
3791 	kn->kn_flags |= EV_CLEAR;
3792 	knlist_add(&fs_knlist, kn, 0);
3793 	return (0);
3794 }
3795 
3796 static void
3797 filt_fsdetach(struct knote *kn)
3798 {
3799 
3800 	knlist_remove(&fs_knlist, kn, 0);
3801 }
3802 
3803 static int
3804 filt_fsevent(struct knote *kn, long hint)
3805 {
3806 
3807 	kn->kn_fflags |= hint;
3808 	return (kn->kn_fflags != 0);
3809 }
3810 
3811 static int
3812 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
3813 {
3814 	struct vfsidctl vc;
3815 	int error;
3816 	struct mount *mp;
3817 
3818 	error = SYSCTL_IN(req, &vc, sizeof(vc));
3819 	if (error)
3820 		return (error);
3821 	if (vc.vc_vers != VFS_CTL_VERS1)
3822 		return (EINVAL);
3823 	mp = vfs_getvfs(&vc.vc_fsid);
3824 	if (mp == NULL)
3825 		return (ENOENT);
3826 	/* ensure that a specific sysctl goes to the right filesystem. */
3827 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
3828 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
3829 		vfs_rel(mp);
3830 		return (EINVAL);
3831 	}
3832 	VCTLTOREQ(&vc, req);
3833 	error = VFS_SYSCTL(mp, vc.vc_op, req);
3834 	vfs_rel(mp);
3835 	return (error);
3836 }
3837 
3838 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
3839     "Sysctl by fsid");
3840 
3841 /*
3842  * Function to initialize a va_filerev field sensibly.
3843  * XXX: Wouldn't a random number make a lot more sense ??
3844  */
3845 u_quad_t
3846 init_va_filerev(void)
3847 {
3848 	struct bintime bt;
3849 
3850 	getbinuptime(&bt);
3851 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
3852 }
3853 
3854 static int	filt_vfsread(struct knote *kn, long hint);
3855 static int	filt_vfswrite(struct knote *kn, long hint);
3856 static int	filt_vfsvnode(struct knote *kn, long hint);
3857 static void	filt_vfsdetach(struct knote *kn);
3858 static struct filterops vfsread_filtops =
3859 	{ 1, NULL, filt_vfsdetach, filt_vfsread };
3860 static struct filterops vfswrite_filtops =
3861 	{ 1, NULL, filt_vfsdetach, filt_vfswrite };
3862 static struct filterops vfsvnode_filtops =
3863 	{ 1, NULL, filt_vfsdetach, filt_vfsvnode };
3864 
3865 static void
3866 vfs_knllock(void *arg)
3867 {
3868 	struct vnode *vp = arg;
3869 
3870 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3871 }
3872 
3873 static void
3874 vfs_knlunlock(void *arg)
3875 {
3876 	struct vnode *vp = arg;
3877 
3878 	VOP_UNLOCK(vp, 0);
3879 }
3880 
3881 static int
3882 vfs_knllocked(void *arg)
3883 {
3884 	struct vnode *vp = arg;
3885 
3886 	return (VOP_ISLOCKED(vp) == LK_EXCLUSIVE);
3887 }
3888 
3889 int
3890 vfs_kqfilter(struct vop_kqfilter_args *ap)
3891 {
3892 	struct vnode *vp = ap->a_vp;
3893 	struct knote *kn = ap->a_kn;
3894 	struct knlist *knl;
3895 
3896 	switch (kn->kn_filter) {
3897 	case EVFILT_READ:
3898 		kn->kn_fop = &vfsread_filtops;
3899 		break;
3900 	case EVFILT_WRITE:
3901 		kn->kn_fop = &vfswrite_filtops;
3902 		break;
3903 	case EVFILT_VNODE:
3904 		kn->kn_fop = &vfsvnode_filtops;
3905 		break;
3906 	default:
3907 		return (EINVAL);
3908 	}
3909 
3910 	kn->kn_hook = (caddr_t)vp;
3911 
3912 	if (vp->v_pollinfo == NULL)
3913 		v_addpollinfo(vp);
3914 	if (vp->v_pollinfo == NULL)
3915 		return (ENOMEM);
3916 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
3917 	knlist_add(knl, kn, 0);
3918 
3919 	return (0);
3920 }
3921 
3922 /*
3923  * Detach knote from vnode
3924  */
3925 static void
3926 filt_vfsdetach(struct knote *kn)
3927 {
3928 	struct vnode *vp = (struct vnode *)kn->kn_hook;
3929 
3930 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
3931 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
3932 }
3933 
3934 /*ARGSUSED*/
3935 static int
3936 filt_vfsread(struct knote *kn, long hint)
3937 {
3938 	struct vnode *vp = (struct vnode *)kn->kn_hook;
3939 	struct vattr va;
3940 
3941 	/*
3942 	 * filesystem is gone, so set the EOF flag and schedule
3943 	 * the knote for deletion.
3944 	 */
3945 	if (hint == NOTE_REVOKE) {
3946 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3947 		return (1);
3948 	}
3949 
3950 	if (VOP_GETATTR(vp, &va, curthread->td_ucred, curthread))
3951 		return (0);
3952 
3953 	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
3954 	return (kn->kn_data != 0);
3955 }
3956 
3957 /*ARGSUSED*/
3958 static int
3959 filt_vfswrite(struct knote *kn, long hint)
3960 {
3961 	/*
3962 	 * filesystem is gone, so set the EOF flag and schedule
3963 	 * the knote for deletion.
3964 	 */
3965 	if (hint == NOTE_REVOKE)
3966 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3967 
3968 	kn->kn_data = 0;
3969 	return (1);
3970 }
3971 
3972 static int
3973 filt_vfsvnode(struct knote *kn, long hint)
3974 {
3975 	if (kn->kn_sfflags & hint)
3976 		kn->kn_fflags |= hint;
3977 	if (hint == NOTE_REVOKE) {
3978 		kn->kn_flags |= EV_EOF;
3979 		return (1);
3980 	}
3981 	return (kn->kn_fflags != 0);
3982 }
3983 
3984 int
3985 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
3986 {
3987 	int error;
3988 
3989 	if (dp->d_reclen > ap->a_uio->uio_resid)
3990 		return (ENAMETOOLONG);
3991 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
3992 	if (error) {
3993 		if (ap->a_ncookies != NULL) {
3994 			if (ap->a_cookies != NULL)
3995 				free(ap->a_cookies, M_TEMP);
3996 			ap->a_cookies = NULL;
3997 			*ap->a_ncookies = 0;
3998 		}
3999 		return (error);
4000 	}
4001 	if (ap->a_ncookies == NULL)
4002 		return (0);
4003 
4004 	KASSERT(ap->a_cookies,
4005 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4006 
4007 	*ap->a_cookies = realloc(*ap->a_cookies,
4008 	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4009 	(*ap->a_cookies)[*ap->a_ncookies] = off;
4010 	return (0);
4011 }
4012 
4013 /*
4014  * Mark for update the access time of the file if the filesystem
4015  * supports VA_MARK_ATIME.  This functionality is used by execve
4016  * and mmap, so we want to avoid the synchronous I/O implied by
4017  * directly setting va_atime for the sake of efficiency.
4018  */
4019 void
4020 vfs_mark_atime(struct vnode *vp, struct thread *td)
4021 {
4022 	struct vattr atimeattr;
4023 
4024 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
4025 		VATTR_NULL(&atimeattr);
4026 		atimeattr.va_vaflags |= VA_MARK_ATIME;
4027 		(void)VOP_SETATTR(vp, &atimeattr, td->td_ucred, td);
4028 	}
4029 }
4030