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