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