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