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