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