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