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