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