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