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