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