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