xref: /freebsd/sys/kern/vfs_subr.c (revision 64467d2ec3ede11430554fea68b317d27bf4b5c3)
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 	 * We cannot check only for v_usecount > 0 there, since
1941 	 * v_usecount increment is lockless.  Instead check for
1942 	 * v_holdcnt > 1, with the side effect that a parallel vhold()
1943 	 * also aborts freeing this vnode.
1944 	 */
1945 	VI_LOCK(vp);
1946 	if (vp->v_holdcnt > 1) {
1947 		VOP_UNLOCK(vp);
1948 		vdropl_recycle(vp);
1949 		vn_finished_write(vnmp);
1950 		CTR2(KTR_VFS,
1951 		    "%s: impossible to recycle, %p is already referenced",
1952 		    __func__, vp);
1953 		return (EBUSY);
1954 	}
1955 	if (!VN_IS_DOOMED(vp)) {
1956 		if (isvnlru)
1957 			recycles_free_count++;
1958 		else
1959 			counter_u64_add(direct_recycles_free_count, 1);
1960 		vgonel(vp);
1961 	}
1962 	VOP_UNLOCK(vp);
1963 	vdropl_recycle(vp);
1964 	vn_finished_write(vnmp);
1965 	return (0);
1966 }
1967 
1968 /*
1969  * Allocate a new vnode.
1970  *
1971  * The operation never returns an error. Returning an error was disabled
1972  * in r145385 (dated 2005) with the following comment:
1973  *
1974  * XXX Not all VFS_VGET/ffs_vget callers check returns.
1975  *
1976  * Given the age of this commit (almost 15 years at the time of writing this
1977  * comment) restoring the ability to fail requires a significant audit of
1978  * all codepaths.
1979  *
1980  * The routine can try to free a vnode or stall for up to 1 second waiting for
1981  * vnlru to clear things up, but ultimately always performs a M_WAITOK allocation.
1982  */
1983 static u_long vn_alloc_cyclecount;
1984 static u_long vn_alloc_sleeps;
1985 
1986 SYSCTL_ULONG(_vfs_vnode_stats, OID_AUTO, alloc_sleeps, CTLFLAG_RD, &vn_alloc_sleeps, 0,
1987     "Number of times vnode allocation blocked waiting on vnlru");
1988 
1989 static struct vnode * __noinline
1990 vn_alloc_hard(struct mount *mp, u_long rnumvnodes, bool bumped)
1991 {
1992 	u_long rfreevnodes;
1993 
1994 	if (bumped) {
1995 		if (rnumvnodes > desiredvnodes + VNLRU_COUNT_SLOP) {
1996 			atomic_subtract_long(&numvnodes, 1);
1997 			bumped = false;
1998 		}
1999 	}
2000 
2001 	mtx_lock(&vnode_list_mtx);
2002 
2003 	/*
2004 	 * Reload 'numvnodes', as since we acquired the lock, it may have
2005 	 * changed significantly if we waited, and 'rnumvnodes' above was only
2006 	 * actually passed if 'bumped' is true (else it is 0).
2007 	 */
2008 	rnumvnodes = atomic_load_long(&numvnodes);
2009 	if (rnumvnodes + !bumped < desiredvnodes) {
2010 		vn_alloc_cyclecount = 0;
2011 		mtx_unlock(&vnode_list_mtx);
2012 		goto alloc;
2013 	}
2014 
2015 	rfreevnodes = vnlru_read_freevnodes();
2016 	if (vn_alloc_cyclecount++ >= rfreevnodes) {
2017 		vn_alloc_cyclecount = 0;
2018 		vstir = true;
2019 	}
2020 
2021 	/*
2022 	 * Grow the vnode cache if it will not be above its target max after
2023 	 * growing.  Otherwise, if there is at least one free vnode, try to
2024 	 * reclaim 1 item from it before growing the cache (possibly above its
2025 	 * target max if the reclamation failed or is delayed).
2026 	 */
2027 	if (vnlru_free_locked_direct(1) > 0)
2028 		goto alloc;
2029 	mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
2030 	if (mp == NULL || (mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2031 		/*
2032 		 * Wait for space for a new vnode.
2033 		 */
2034 		if (bumped) {
2035 			atomic_subtract_long(&numvnodes, 1);
2036 			bumped = false;
2037 		}
2038 		mtx_lock(&vnode_list_mtx);
2039 		vnlru_kick_locked();
2040 		vn_alloc_sleeps++;
2041 		msleep(&vnlruproc_sig, &vnode_list_mtx, PVFS, "vlruwk", hz);
2042 		if (atomic_load_long(&numvnodes) + 1 > desiredvnodes &&
2043 		    vnlru_read_freevnodes() > 1)
2044 			vnlru_free_locked_direct(1);
2045 		else
2046 			mtx_unlock(&vnode_list_mtx);
2047 	}
2048 alloc:
2049 	mtx_assert(&vnode_list_mtx, MA_NOTOWNED);
2050 	if (!bumped)
2051 		atomic_add_long(&numvnodes, 1);
2052 	vnlru_kick_cond();
2053 	return (uma_zalloc_smr(vnode_zone, M_WAITOK));
2054 }
2055 
2056 static struct vnode *
2057 vn_alloc(struct mount *mp)
2058 {
2059 	u_long rnumvnodes;
2060 
2061 	if (__predict_false(vn_alloc_cyclecount != 0))
2062 		return (vn_alloc_hard(mp, 0, false));
2063 	rnumvnodes = atomic_fetchadd_long(&numvnodes, 1) + 1;
2064 	if (__predict_false(vnlru_under(rnumvnodes, vlowat))) {
2065 		return (vn_alloc_hard(mp, rnumvnodes, true));
2066 	}
2067 
2068 	return (uma_zalloc_smr(vnode_zone, M_WAITOK));
2069 }
2070 
2071 static void
2072 vn_free(struct vnode *vp)
2073 {
2074 
2075 	atomic_subtract_long(&numvnodes, 1);
2076 	uma_zfree_smr(vnode_zone, vp);
2077 }
2078 
2079 /*
2080  * Allocate a new vnode.
2081  */
2082 int
2083 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
2084     struct vnode **vpp)
2085 {
2086 	struct vnode *vp;
2087 	struct thread *td;
2088 	struct lock_object *lo;
2089 
2090 	CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
2091 
2092 	KASSERT(vops->registered,
2093 	    ("%s: not registered vector op %p\n", __func__, vops));
2094 	cache_validate_vop_vector(mp, vops);
2095 
2096 	td = curthread;
2097 	if (td->td_vp_reserved != NULL) {
2098 		vp = td->td_vp_reserved;
2099 		td->td_vp_reserved = NULL;
2100 	} else {
2101 		vp = vn_alloc(mp);
2102 	}
2103 	counter_u64_add(vnodes_created, 1);
2104 
2105 	vn_set_state(vp, VSTATE_UNINITIALIZED);
2106 
2107 	/*
2108 	 * Locks are given the generic name "vnode" when created.
2109 	 * Follow the historic practice of using the filesystem
2110 	 * name when they allocated, e.g., "zfs", "ufs", "nfs, etc.
2111 	 *
2112 	 * Locks live in a witness group keyed on their name. Thus,
2113 	 * when a lock is renamed, it must also move from the witness
2114 	 * group of its old name to the witness group of its new name.
2115 	 *
2116 	 * The change only needs to be made when the vnode moves
2117 	 * from one filesystem type to another. We ensure that each
2118 	 * filesystem use a single static name pointer for its tag so
2119 	 * that we can compare pointers rather than doing a strcmp().
2120 	 */
2121 	lo = &vp->v_vnlock->lock_object;
2122 #ifdef WITNESS
2123 	if (lo->lo_name != tag) {
2124 #endif
2125 		lo->lo_name = tag;
2126 #ifdef WITNESS
2127 		WITNESS_DESTROY(lo);
2128 		WITNESS_INIT(lo, tag);
2129 	}
2130 #endif
2131 	/*
2132 	 * By default, don't allow shared locks unless filesystems opt-in.
2133 	 */
2134 	vp->v_vnlock->lock_object.lo_flags |= LK_NOSHARE;
2135 	/*
2136 	 * Finalize various vnode identity bits.
2137 	 */
2138 	KASSERT(vp->v_object == NULL, ("stale v_object %p", vp));
2139 	KASSERT(vp->v_lockf == NULL, ("stale v_lockf %p", vp));
2140 	KASSERT(vp->v_pollinfo == NULL, ("stale v_pollinfo %p", vp));
2141 	vp->v_type = VNON;
2142 	vp->v_op = vops;
2143 	vp->v_irflag = 0;
2144 	v_init_counters(vp);
2145 	vn_seqc_init(vp);
2146 	vp->v_bufobj.bo_ops = &buf_ops_bio;
2147 #ifdef DIAGNOSTIC
2148 	if (mp == NULL && vops != &dead_vnodeops)
2149 		printf("NULL mp in getnewvnode(9), tag %s\n", tag);
2150 #endif
2151 #ifdef MAC
2152 	mac_vnode_init(vp);
2153 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
2154 		mac_vnode_associate_singlelabel(mp, vp);
2155 #endif
2156 	if (mp != NULL) {
2157 		vp->v_bufobj.bo_bsize = mp->mnt_stat.f_iosize;
2158 	}
2159 
2160 	/*
2161 	 * For the filesystems which do not use vfs_hash_insert(),
2162 	 * still initialize v_hash to have vfs_hash_index() useful.
2163 	 * E.g., nullfs uses vfs_hash_index() on the lower vnode for
2164 	 * its own hashing.
2165 	 */
2166 	vp->v_hash = (uintptr_t)vp >> vnsz2log;
2167 
2168 	*vpp = vp;
2169 	return (0);
2170 }
2171 
2172 void
2173 getnewvnode_reserve(void)
2174 {
2175 	struct thread *td;
2176 
2177 	td = curthread;
2178 	MPASS(td->td_vp_reserved == NULL);
2179 	td->td_vp_reserved = vn_alloc(NULL);
2180 }
2181 
2182 void
2183 getnewvnode_drop_reserve(void)
2184 {
2185 	struct thread *td;
2186 
2187 	td = curthread;
2188 	if (td->td_vp_reserved != NULL) {
2189 		vn_free(td->td_vp_reserved);
2190 		td->td_vp_reserved = NULL;
2191 	}
2192 }
2193 
2194 static void __noinline
2195 freevnode(struct vnode *vp)
2196 {
2197 	struct bufobj *bo;
2198 
2199 	ASSERT_VOP_UNLOCKED(vp, __func__);
2200 
2201 	/*
2202 	 * The vnode has been marked for destruction, so free it.
2203 	 *
2204 	 * The vnode will be returned to the zone where it will
2205 	 * normally remain until it is needed for another vnode. We
2206 	 * need to cleanup (or verify that the cleanup has already
2207 	 * been done) any residual data left from its current use
2208 	 * so as not to contaminate the freshly allocated vnode.
2209 	 */
2210 	CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__, vp);
2211 	/*
2212 	 * Paired with vgone.
2213 	 */
2214 	vn_seqc_write_end_free(vp);
2215 
2216 	bo = &vp->v_bufobj;
2217 	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
2218 	VNPASS(vp->v_holdcnt == VHOLD_NO_SMR, vp);
2219 	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
2220 	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
2221 	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
2222 	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
2223 	VNASSERT(pctrie_is_empty(&bo->bo_clean.bv_root), vp,
2224 	    ("clean blk trie not empty"));
2225 	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
2226 	VNASSERT(pctrie_is_empty(&bo->bo_dirty.bv_root), vp,
2227 	    ("dirty blk trie not empty"));
2228 	VNASSERT((vp->v_iflag & (VI_DOINGINACT | VI_OWEINACT)) == 0, vp,
2229 	    ("Leaked inactivation"));
2230 	VI_UNLOCK(vp);
2231 	cache_assert_no_entries(vp);
2232 
2233 #ifdef MAC
2234 	mac_vnode_destroy(vp);
2235 #endif
2236 	if (vp->v_pollinfo != NULL) {
2237 		int error __diagused;
2238 
2239 		/*
2240 		 * Use LK_NOWAIT to shut up witness about the lock. We may get
2241 		 * here while having another vnode locked when trying to
2242 		 * satisfy a lookup and needing to recycle.
2243 		 */
2244 		error = VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT);
2245 		VNASSERT(error == 0, vp,
2246 		    ("freevnode: cannot lock vp %p for pollinfo destroy", vp));
2247 		destroy_vpollinfo(vp->v_pollinfo);
2248 		VOP_UNLOCK(vp);
2249 		vp->v_pollinfo = NULL;
2250 	}
2251 	vp->v_mountedhere = NULL;
2252 	vp->v_unpcb = NULL;
2253 	vp->v_rdev = NULL;
2254 	vp->v_fifoinfo = NULL;
2255 	vp->v_iflag = 0;
2256 	vp->v_vflag = 0;
2257 	bo->bo_flag = 0;
2258 	vn_free(vp);
2259 }
2260 
2261 /*
2262  * Delete from old mount point vnode list, if on one.
2263  */
2264 static void
2265 delmntque(struct vnode *vp)
2266 {
2267 	struct mount *mp;
2268 
2269 	VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
2270 
2271 	mp = vp->v_mount;
2272 	MNT_ILOCK(mp);
2273 	VI_LOCK(vp);
2274 	vp->v_mount = NULL;
2275 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
2276 		("bad mount point vnode list size"));
2277 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2278 	mp->mnt_nvnodelistsize--;
2279 	MNT_REL(mp);
2280 	MNT_IUNLOCK(mp);
2281 	/*
2282 	 * The caller expects the interlock to be still held.
2283 	 */
2284 	ASSERT_VI_LOCKED(vp, __func__);
2285 }
2286 
2287 static int
2288 insmntque1_int(struct vnode *vp, struct mount *mp, bool dtr)
2289 {
2290 
2291 	KASSERT(vp->v_mount == NULL,
2292 		("insmntque: vnode already on per mount vnode list"));
2293 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
2294 	if ((mp->mnt_kern_flag & MNTK_UNLOCKED_INSMNTQUE) == 0) {
2295 		ASSERT_VOP_ELOCKED(vp, "insmntque: non-locked vp");
2296 	} else {
2297 		KASSERT(!dtr,
2298 		    ("%s: can't have MNTK_UNLOCKED_INSMNTQUE and cleanup",
2299 		    __func__));
2300 	}
2301 
2302 	/*
2303 	 * We acquire the vnode interlock early to ensure that the
2304 	 * vnode cannot be recycled by another process releasing a
2305 	 * holdcnt on it before we get it on both the vnode list
2306 	 * and the active vnode list. The mount mutex protects only
2307 	 * manipulation of the vnode list and the vnode freelist
2308 	 * mutex protects only manipulation of the active vnode list.
2309 	 * Hence the need to hold the vnode interlock throughout.
2310 	 */
2311 	MNT_ILOCK(mp);
2312 	VI_LOCK(vp);
2313 	if (((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
2314 	    ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
2315 	    mp->mnt_nvnodelistsize == 0)) &&
2316 	    (vp->v_vflag & VV_FORCEINSMQ) == 0) {
2317 		VI_UNLOCK(vp);
2318 		MNT_IUNLOCK(mp);
2319 		if (dtr) {
2320 			vp->v_data = NULL;
2321 			vp->v_op = &dead_vnodeops;
2322 			vgone(vp);
2323 			vput(vp);
2324 		}
2325 		return (EBUSY);
2326 	}
2327 	vp->v_mount = mp;
2328 	MNT_REF(mp);
2329 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2330 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
2331 		("neg mount point vnode list size"));
2332 	mp->mnt_nvnodelistsize++;
2333 	VI_UNLOCK(vp);
2334 	MNT_IUNLOCK(mp);
2335 	return (0);
2336 }
2337 
2338 /*
2339  * Insert into list of vnodes for the new mount point, if available.
2340  * insmntque() reclaims the vnode on insertion failure, insmntque1()
2341  * leaves handling of the vnode to the caller.
2342  */
2343 int
2344 insmntque(struct vnode *vp, struct mount *mp)
2345 {
2346 	return (insmntque1_int(vp, mp, true));
2347 }
2348 
2349 int
2350 insmntque1(struct vnode *vp, struct mount *mp)
2351 {
2352 	return (insmntque1_int(vp, mp, false));
2353 }
2354 
2355 /*
2356  * Flush out and invalidate all buffers associated with a bufobj
2357  * Called with the underlying object locked.
2358  */
2359 int
2360 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
2361 {
2362 	int error;
2363 
2364 	BO_LOCK(bo);
2365 	if (flags & V_SAVE) {
2366 		error = bufobj_wwait(bo, slpflag, slptimeo);
2367 		if (error) {
2368 			BO_UNLOCK(bo);
2369 			return (error);
2370 		}
2371 		if (bo->bo_dirty.bv_cnt > 0) {
2372 			BO_UNLOCK(bo);
2373 			do {
2374 				error = BO_SYNC(bo, MNT_WAIT);
2375 			} while (error == ERELOOKUP);
2376 			if (error != 0)
2377 				return (error);
2378 			BO_LOCK(bo);
2379 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0) {
2380 				BO_UNLOCK(bo);
2381 				return (EBUSY);
2382 			}
2383 		}
2384 	}
2385 	/*
2386 	 * If you alter this loop please notice that interlock is dropped and
2387 	 * reacquired in flushbuflist.  Special care is needed to ensure that
2388 	 * no race conditions occur from this.
2389 	 */
2390 	do {
2391 		error = flushbuflist(&bo->bo_clean,
2392 		    flags, bo, slpflag, slptimeo);
2393 		if (error == 0 && !(flags & V_CLEANONLY))
2394 			error = flushbuflist(&bo->bo_dirty,
2395 			    flags, bo, slpflag, slptimeo);
2396 		if (error != 0 && error != EAGAIN) {
2397 			BO_UNLOCK(bo);
2398 			return (error);
2399 		}
2400 	} while (error != 0);
2401 
2402 	/*
2403 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
2404 	 * have write I/O in-progress but if there is a VM object then the
2405 	 * VM object can also have read-I/O in-progress.
2406 	 */
2407 	do {
2408 		bufobj_wwait(bo, 0, 0);
2409 		if ((flags & V_VMIO) == 0 && bo->bo_object != NULL) {
2410 			BO_UNLOCK(bo);
2411 			vm_object_pip_wait_unlocked(bo->bo_object, "bovlbx");
2412 			BO_LOCK(bo);
2413 		}
2414 	} while (bo->bo_numoutput > 0);
2415 	BO_UNLOCK(bo);
2416 
2417 	/*
2418 	 * Destroy the copy in the VM cache, too.
2419 	 */
2420 	if (bo->bo_object != NULL &&
2421 	    (flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0) {
2422 		VM_OBJECT_WLOCK(bo->bo_object);
2423 		vm_object_page_remove(bo->bo_object, 0, 0, (flags & V_SAVE) ?
2424 		    OBJPR_CLEANONLY : 0);
2425 		VM_OBJECT_WUNLOCK(bo->bo_object);
2426 	}
2427 
2428 #ifdef INVARIANTS
2429 	BO_LOCK(bo);
2430 	if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO |
2431 	    V_ALLOWCLEAN)) == 0 && (bo->bo_dirty.bv_cnt > 0 ||
2432 	    bo->bo_clean.bv_cnt > 0))
2433 		panic("vinvalbuf: flush failed");
2434 	if ((flags & (V_ALT | V_NORMAL | V_CLEANONLY | V_VMIO)) == 0 &&
2435 	    bo->bo_dirty.bv_cnt > 0)
2436 		panic("vinvalbuf: flush dirty failed");
2437 	BO_UNLOCK(bo);
2438 #endif
2439 	return (0);
2440 }
2441 
2442 /*
2443  * Flush out and invalidate all buffers associated with a vnode.
2444  * Called with the underlying object locked.
2445  */
2446 int
2447 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
2448 {
2449 
2450 	CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2451 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
2452 	if (vp->v_object != NULL && vp->v_object->handle != vp)
2453 		return (0);
2454 	return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
2455 }
2456 
2457 /*
2458  * Flush out buffers on the specified list.
2459  *
2460  */
2461 static int
2462 flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
2463     int slptimeo)
2464 {
2465 	struct buf *bp, *nbp;
2466 	int retval, error;
2467 	daddr_t lblkno;
2468 	b_xflags_t xflags;
2469 
2470 	ASSERT_BO_WLOCKED(bo);
2471 
2472 	retval = 0;
2473 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
2474 		/*
2475 		 * If we are flushing both V_NORMAL and V_ALT buffers then
2476 		 * do not skip any buffers. If we are flushing only V_NORMAL
2477 		 * buffers then skip buffers marked as BX_ALTDATA. If we are
2478 		 * flushing only V_ALT buffers then skip buffers not marked
2479 		 * as BX_ALTDATA.
2480 		 */
2481 		if (((flags & (V_NORMAL | V_ALT)) != (V_NORMAL | V_ALT)) &&
2482 		   (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA) != 0) ||
2483 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0))) {
2484 			continue;
2485 		}
2486 		if (nbp != NULL) {
2487 			lblkno = nbp->b_lblkno;
2488 			xflags = nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN);
2489 		}
2490 		retval = EAGAIN;
2491 		error = BUF_TIMELOCK(bp,
2492 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_LOCKPTR(bo),
2493 		    "flushbuf", slpflag, slptimeo);
2494 		if (error) {
2495 			BO_LOCK(bo);
2496 			return (error != ENOLCK ? error : EAGAIN);
2497 		}
2498 		KASSERT(bp->b_bufobj == bo,
2499 		    ("bp %p wrong b_bufobj %p should be %p",
2500 		    bp, bp->b_bufobj, bo));
2501 		/*
2502 		 * XXX Since there are no node locks for NFS, I
2503 		 * believe there is a slight chance that a delayed
2504 		 * write will occur while sleeping just above, so
2505 		 * check for it.
2506 		 */
2507 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
2508 		    (flags & V_SAVE)) {
2509 			bremfree(bp);
2510 			bp->b_flags |= B_ASYNC;
2511 			bwrite(bp);
2512 			BO_LOCK(bo);
2513 			return (EAGAIN);	/* XXX: why not loop ? */
2514 		}
2515 		bremfree(bp);
2516 		bp->b_flags |= (B_INVAL | B_RELBUF);
2517 		bp->b_flags &= ~B_ASYNC;
2518 		brelse(bp);
2519 		BO_LOCK(bo);
2520 		if (nbp == NULL)
2521 			break;
2522 		nbp = gbincore(bo, lblkno);
2523 		if (nbp == NULL || (nbp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
2524 		    != xflags)
2525 			break;			/* nbp invalid */
2526 	}
2527 	return (retval);
2528 }
2529 
2530 int
2531 bnoreuselist(struct bufv *bufv, struct bufobj *bo, daddr_t startn, daddr_t endn)
2532 {
2533 	struct buf *bp;
2534 	int error;
2535 	daddr_t lblkno;
2536 
2537 	ASSERT_BO_LOCKED(bo);
2538 
2539 	for (lblkno = startn;;) {
2540 again:
2541 		bp = buf_lookup_ge(bufv, lblkno);
2542 		if (bp == NULL || bp->b_lblkno >= endn)
2543 			break;
2544 		error = BUF_TIMELOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
2545 		    LK_INTERLOCK, BO_LOCKPTR(bo), "brlsfl", 0, 0);
2546 		if (error != 0) {
2547 			BO_RLOCK(bo);
2548 			if (error == ENOLCK)
2549 				goto again;
2550 			return (error);
2551 		}
2552 		KASSERT(bp->b_bufobj == bo,
2553 		    ("bp %p wrong b_bufobj %p should be %p",
2554 		    bp, bp->b_bufobj, bo));
2555 		lblkno = bp->b_lblkno + 1;
2556 		if ((bp->b_flags & B_MANAGED) == 0)
2557 			bremfree(bp);
2558 		bp->b_flags |= B_RELBUF;
2559 		/*
2560 		 * In the VMIO case, use the B_NOREUSE flag to hint that the
2561 		 * pages backing each buffer in the range are unlikely to be
2562 		 * reused.  Dirty buffers will have the hint applied once
2563 		 * they've been written.
2564 		 */
2565 		if ((bp->b_flags & B_VMIO) != 0)
2566 			bp->b_flags |= B_NOREUSE;
2567 		brelse(bp);
2568 		BO_RLOCK(bo);
2569 	}
2570 	return (0);
2571 }
2572 
2573 /*
2574  * Truncate a file's buffer and pages to a specified length.  This
2575  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
2576  * sync activity.
2577  */
2578 int
2579 vtruncbuf(struct vnode *vp, off_t length, int blksize)
2580 {
2581 	struct buf *bp, *nbp;
2582 	struct bufobj *bo;
2583 	daddr_t startlbn;
2584 
2585 	CTR4(KTR_VFS, "%s: vp %p with block %d:%ju", __func__,
2586 	    vp, blksize, (uintmax_t)length);
2587 
2588 	/*
2589 	 * Round up to the *next* lbn.
2590 	 */
2591 	startlbn = howmany(length, blksize);
2592 
2593 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
2594 
2595 	bo = &vp->v_bufobj;
2596 restart_unlocked:
2597 	BO_LOCK(bo);
2598 
2599 	while (v_inval_buf_range_locked(vp, bo, startlbn, INT64_MAX) == EAGAIN)
2600 		;
2601 
2602 	if (length > 0) {
2603 		/*
2604 		 * Write out vnode metadata, e.g. indirect blocks.
2605 		 */
2606 restartsync:
2607 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2608 			if (bp->b_lblkno >= 0)
2609 				continue;
2610 			/*
2611 			 * Since we hold the vnode lock this should only
2612 			 * fail if we're racing with the buf daemon.
2613 			 */
2614 			if (BUF_LOCK(bp,
2615 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2616 			    BO_LOCKPTR(bo)) == ENOLCK)
2617 				goto restart_unlocked;
2618 
2619 			VNASSERT((bp->b_flags & B_DELWRI), vp,
2620 			    ("buf(%p) on dirty queue without DELWRI", bp));
2621 
2622 			bremfree(bp);
2623 			bawrite(bp);
2624 			BO_LOCK(bo);
2625 			goto restartsync;
2626 		}
2627 	}
2628 
2629 	bufobj_wwait(bo, 0, 0);
2630 	BO_UNLOCK(bo);
2631 	vnode_pager_setsize(vp, length);
2632 
2633 	return (0);
2634 }
2635 
2636 /*
2637  * Invalidate the cached pages of a file's buffer within the range of block
2638  * numbers [startlbn, endlbn).
2639  */
2640 void
2641 v_inval_buf_range(struct vnode *vp, daddr_t startlbn, daddr_t endlbn,
2642     int blksize)
2643 {
2644 	struct bufobj *bo;
2645 	off_t start, end;
2646 
2647 	ASSERT_VOP_LOCKED(vp, "v_inval_buf_range");
2648 
2649 	start = blksize * startlbn;
2650 	end = blksize * endlbn;
2651 
2652 	bo = &vp->v_bufobj;
2653 	BO_LOCK(bo);
2654 	MPASS(blksize == bo->bo_bsize);
2655 
2656 	while (v_inval_buf_range_locked(vp, bo, startlbn, endlbn) == EAGAIN)
2657 		;
2658 
2659 	BO_UNLOCK(bo);
2660 	vn_pages_remove(vp, OFF_TO_IDX(start), OFF_TO_IDX(end + PAGE_SIZE - 1));
2661 }
2662 
2663 static int
2664 v_inval_buf_range_locked(struct vnode *vp, struct bufobj *bo,
2665     daddr_t startlbn, daddr_t endlbn)
2666 {
2667 	struct bufv *bv;
2668 	struct buf *bp, *nbp;
2669 	uint8_t anyfreed;
2670 	bool clean;
2671 
2672 	ASSERT_VOP_LOCKED(vp, "v_inval_buf_range_locked");
2673 	ASSERT_BO_LOCKED(bo);
2674 
2675 	anyfreed = 1;
2676 	clean = true;
2677 	do {
2678 		bv = clean ? &bo->bo_clean : &bo->bo_dirty;
2679 		bp = buf_lookup_ge(bv, startlbn);
2680 		if (bp == NULL)
2681 			continue;
2682 		TAILQ_FOREACH_FROM_SAFE(bp, &bv->bv_hd, b_bobufs, nbp) {
2683 			if (bp->b_lblkno >= endlbn)
2684 				break;
2685 			if (BUF_LOCK(bp,
2686 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
2687 			    BO_LOCKPTR(bo)) == ENOLCK) {
2688 				BO_LOCK(bo);
2689 				return (EAGAIN);
2690 			}
2691 
2692 			bremfree(bp);
2693 			bp->b_flags |= B_INVAL | B_RELBUF;
2694 			bp->b_flags &= ~B_ASYNC;
2695 			brelse(bp);
2696 			anyfreed = 2;
2697 
2698 			BO_LOCK(bo);
2699 			if (nbp != NULL &&
2700 			    (((nbp->b_xflags &
2701 			    (clean ? BX_VNCLEAN : BX_VNDIRTY)) == 0) ||
2702 			    nbp->b_vp != vp ||
2703 			    (nbp->b_flags & B_DELWRI) == (clean? B_DELWRI: 0)))
2704 				return (EAGAIN);
2705 		}
2706 	} while (clean = !clean, anyfreed-- > 0);
2707 	return (0);
2708 }
2709 
2710 static void
2711 buf_vlist_remove(struct buf *bp)
2712 {
2713 	struct bufv *bv;
2714 	b_xflags_t flags;
2715 
2716 	flags = bp->b_xflags;
2717 
2718 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
2719 	ASSERT_BO_WLOCKED(bp->b_bufobj);
2720 	KASSERT((flags & (BX_VNDIRTY | BX_VNCLEAN)) != 0 &&
2721 	    (flags & (BX_VNDIRTY | BX_VNCLEAN)) != (BX_VNDIRTY | BX_VNCLEAN),
2722 	    ("%s: buffer %p has invalid queue state", __func__, bp));
2723 
2724 	if ((flags & BX_VNDIRTY) != 0)
2725 		bv = &bp->b_bufobj->bo_dirty;
2726 	else
2727 		bv = &bp->b_bufobj->bo_clean;
2728 	BUF_PCTRIE_REMOVE(&bv->bv_root, bp->b_lblkno);
2729 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
2730 	bv->bv_cnt--;
2731 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
2732 }
2733 
2734 /*
2735  * Add the buffer to the sorted clean or dirty block list.  Return zero on
2736  * success, EEXIST if a buffer with this identity already exists, or another
2737  * error on allocation failure.
2738  */
2739 static inline int
2740 buf_vlist_find_or_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2741 {
2742 	struct bufv *bv;
2743 	struct buf *n;
2744 	int error;
2745 
2746 	ASSERT_BO_WLOCKED(bo);
2747 	KASSERT((bo->bo_flag & BO_NOBUFS) == 0,
2748 	    ("buf_vlist_add: bo %p does not allow bufs", bo));
2749 	KASSERT((xflags & BX_VNDIRTY) == 0 || (bo->bo_flag & BO_DEAD) == 0,
2750 	    ("dead bo %p", bo));
2751 	KASSERT((bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) == xflags,
2752 	    ("buf_vlist_add: b_xflags %#x not set on bp %p", xflags, bp));
2753 
2754 	if (xflags & BX_VNDIRTY)
2755 		bv = &bo->bo_dirty;
2756 	else
2757 		bv = &bo->bo_clean;
2758 
2759 	error = buf_insert_lookup_le(bv, bp, &n);
2760 	if (n == NULL) {
2761 		KASSERT(error != EEXIST,
2762 		    ("buf_vlist_add: EEXIST but no existing buf found: bp %p",
2763 		    bp));
2764 	} else {
2765 		KASSERT(n->b_lblkno <= bp->b_lblkno,
2766 		    ("buf_vlist_add: out of order insert/lookup: bp %p n %p",
2767 		    bp, n));
2768 		KASSERT((n->b_lblkno == bp->b_lblkno) == (error == EEXIST),
2769 		    ("buf_vlist_add: inconsistent result for existing buf: "
2770 		    "error %d bp %p n %p", error, bp, n));
2771 	}
2772 	if (error != 0)
2773 		return (error);
2774 
2775 	/* Keep the list ordered. */
2776 	if (n == NULL) {
2777 		KASSERT(TAILQ_EMPTY(&bv->bv_hd) ||
2778 		    bp->b_lblkno < TAILQ_FIRST(&bv->bv_hd)->b_lblkno,
2779 		    ("buf_vlist_add: queue order: "
2780 		    "%p should be before first %p",
2781 		    bp, TAILQ_FIRST(&bv->bv_hd)));
2782 		TAILQ_INSERT_HEAD(&bv->bv_hd, bp, b_bobufs);
2783 	} else {
2784 		KASSERT(TAILQ_NEXT(n, b_bobufs) == NULL ||
2785 		    bp->b_lblkno < TAILQ_NEXT(n, b_bobufs)->b_lblkno,
2786 		    ("buf_vlist_add: queue order: "
2787 		    "%p should be before next %p",
2788 		    bp, TAILQ_NEXT(n, b_bobufs)));
2789 		TAILQ_INSERT_AFTER(&bv->bv_hd, n, bp, b_bobufs);
2790 	}
2791 
2792 	bv->bv_cnt++;
2793 	return (0);
2794 }
2795 
2796 /*
2797  * Add the buffer to the sorted clean or dirty block list.
2798  *
2799  * NOTE: xflags is passed as a constant, optimizing this inline function!
2800  */
2801 static void
2802 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
2803 {
2804 	int error;
2805 
2806 	KASSERT((bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) == 0,
2807 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
2808 	bp->b_xflags |= xflags;
2809 	error = buf_vlist_find_or_add(bp, bo, xflags);
2810 	if (error)
2811 		panic("buf_vlist_add: error=%d", error);
2812 }
2813 
2814 /*
2815  * Look up a buffer using the buffer tries.
2816  */
2817 struct buf *
2818 gbincore(struct bufobj *bo, daddr_t lblkno)
2819 {
2820 	struct buf *bp;
2821 
2822 	ASSERT_BO_LOCKED(bo);
2823 	bp = BUF_PCTRIE_LOOKUP(&bo->bo_clean.bv_root, lblkno);
2824 	if (bp != NULL)
2825 		return (bp);
2826 	return (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, lblkno));
2827 }
2828 
2829 /*
2830  * Look up a buf using the buffer tries, without the bufobj lock.  This relies
2831  * on SMR for safe lookup, and bufs being in a no-free zone to provide type
2832  * stability of the result.  Like other lockless lookups, the found buf may
2833  * already be invalid by the time this function returns.
2834  */
2835 struct buf *
2836 gbincore_unlocked(struct bufobj *bo, daddr_t lblkno)
2837 {
2838 	struct buf *bp;
2839 
2840 	ASSERT_BO_UNLOCKED(bo);
2841 	bp = BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_clean.bv_root, lblkno);
2842 	if (bp != NULL)
2843 		return (bp);
2844 	return (BUF_PCTRIE_LOOKUP_UNLOCKED(&bo->bo_dirty.bv_root, lblkno));
2845 }
2846 
2847 /*
2848  * Associate a buffer with a vnode.
2849  */
2850 int
2851 bgetvp(struct vnode *vp, struct buf *bp)
2852 {
2853 	struct bufobj *bo;
2854 	int error;
2855 
2856 	bo = &vp->v_bufobj;
2857 	ASSERT_BO_UNLOCKED(bo);
2858 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
2859 
2860 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
2861 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
2862 	    ("bgetvp: bp already attached! %p", bp));
2863 
2864 	/*
2865 	 * Add the buf to the vnode's clean list unless we lost a race and find
2866 	 * an existing buf in either dirty or clean.
2867 	 */
2868 	bp->b_vp = vp;
2869 	bp->b_bufobj = bo;
2870 	bp->b_xflags |= BX_VNCLEAN;
2871 	error = EEXIST;
2872 	BO_LOCK(bo);
2873 	if (BUF_PCTRIE_LOOKUP(&bo->bo_dirty.bv_root, bp->b_lblkno) == NULL)
2874 		error = buf_vlist_find_or_add(bp, bo, BX_VNCLEAN);
2875 	BO_UNLOCK(bo);
2876 	if (__predict_true(error == 0)) {
2877 		vhold(vp);
2878 		return (0);
2879 	}
2880 	if (error != EEXIST)
2881 		panic("bgetvp: buf_vlist_add error: %d", error);
2882 	bp->b_vp = NULL;
2883 	bp->b_bufobj = NULL;
2884 	bp->b_xflags &= ~BX_VNCLEAN;
2885 	return (error);
2886 }
2887 
2888 /*
2889  * Disassociate a buffer from a vnode.
2890  */
2891 void
2892 brelvp(struct buf *bp)
2893 {
2894 	struct bufobj *bo;
2895 	struct vnode *vp;
2896 
2897 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
2898 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
2899 
2900 	/*
2901 	 * Delete from old vnode list, if on one.
2902 	 */
2903 	vp = bp->b_vp;		/* XXX */
2904 	bo = bp->b_bufobj;
2905 	BO_LOCK(bo);
2906 	buf_vlist_remove(bp);
2907 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
2908 		bo->bo_flag &= ~BO_ONWORKLST;
2909 		mtx_lock(&sync_mtx);
2910 		LIST_REMOVE(bo, bo_synclist);
2911 		syncer_worklist_len--;
2912 		mtx_unlock(&sync_mtx);
2913 	}
2914 	bp->b_vp = NULL;
2915 	bp->b_bufobj = NULL;
2916 	BO_UNLOCK(bo);
2917 	vdrop(vp);
2918 }
2919 
2920 /*
2921  * Add an item to the syncer work queue.
2922  */
2923 static void
2924 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
2925 {
2926 	int slot;
2927 
2928 	ASSERT_BO_WLOCKED(bo);
2929 
2930 	mtx_lock(&sync_mtx);
2931 	if (bo->bo_flag & BO_ONWORKLST)
2932 		LIST_REMOVE(bo, bo_synclist);
2933 	else {
2934 		bo->bo_flag |= BO_ONWORKLST;
2935 		syncer_worklist_len++;
2936 	}
2937 
2938 	if (delay > syncer_maxdelay - 2)
2939 		delay = syncer_maxdelay - 2;
2940 	slot = (syncer_delayno + delay) & syncer_mask;
2941 
2942 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
2943 	mtx_unlock(&sync_mtx);
2944 }
2945 
2946 static int
2947 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
2948 {
2949 	int error, len;
2950 
2951 	mtx_lock(&sync_mtx);
2952 	len = syncer_worklist_len - sync_vnode_count;
2953 	mtx_unlock(&sync_mtx);
2954 	error = SYSCTL_OUT(req, &len, sizeof(len));
2955 	return (error);
2956 }
2957 
2958 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len,
2959     CTLTYPE_INT | CTLFLAG_MPSAFE| CTLFLAG_RD, NULL, 0,
2960     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
2961 
2962 static struct proc *updateproc;
2963 static void sched_sync(void);
2964 static struct kproc_desc up_kp = {
2965 	"syncer",
2966 	sched_sync,
2967 	&updateproc
2968 };
2969 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
2970 
2971 static int
2972 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
2973 {
2974 	struct vnode *vp;
2975 	struct mount *mp;
2976 
2977 	*bo = LIST_FIRST(slp);
2978 	if (*bo == NULL)
2979 		return (0);
2980 	vp = bo2vnode(*bo);
2981 	if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
2982 		return (1);
2983 	/*
2984 	 * We use vhold in case the vnode does not
2985 	 * successfully sync.  vhold prevents the vnode from
2986 	 * going away when we unlock the sync_mtx so that
2987 	 * we can acquire the vnode interlock.
2988 	 */
2989 	vholdl(vp);
2990 	mtx_unlock(&sync_mtx);
2991 	VI_UNLOCK(vp);
2992 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
2993 		vdrop(vp);
2994 		mtx_lock(&sync_mtx);
2995 		return (*bo == LIST_FIRST(slp));
2996 	}
2997 	MPASSERT(mp == NULL || (curthread->td_pflags & TDP_IGNSUSP) != 0 ||
2998 	    (mp->mnt_kern_flag & MNTK_SUSPENDED) == 0, mp,
2999 	    ("suspended mp syncing vp %p", vp));
3000 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3001 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
3002 	VOP_UNLOCK(vp);
3003 	vn_finished_write(mp);
3004 	BO_LOCK(*bo);
3005 	if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
3006 		/*
3007 		 * Put us back on the worklist.  The worklist
3008 		 * routine will remove us from our current
3009 		 * position and then add us back in at a later
3010 		 * position.
3011 		 */
3012 		vn_syncer_add_to_worklist(*bo, syncdelay);
3013 	}
3014 	BO_UNLOCK(*bo);
3015 	vdrop(vp);
3016 	mtx_lock(&sync_mtx);
3017 	return (0);
3018 }
3019 
3020 static int first_printf = 1;
3021 
3022 /*
3023  * System filesystem synchronizer daemon.
3024  */
3025 static void
3026 sched_sync(void)
3027 {
3028 	struct synclist *next, *slp;
3029 	struct bufobj *bo;
3030 	long starttime;
3031 	struct thread *td = curthread;
3032 	int last_work_seen;
3033 	int net_worklist_len;
3034 	int syncer_final_iter;
3035 	int error;
3036 
3037 	last_work_seen = 0;
3038 	syncer_final_iter = 0;
3039 	syncer_state = SYNCER_RUNNING;
3040 	starttime = time_uptime;
3041 	td->td_pflags |= TDP_NORUNNINGBUF;
3042 
3043 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
3044 	    SHUTDOWN_PRI_LAST);
3045 
3046 	mtx_lock(&sync_mtx);
3047 	for (;;) {
3048 		if (syncer_state == SYNCER_FINAL_DELAY &&
3049 		    syncer_final_iter == 0) {
3050 			mtx_unlock(&sync_mtx);
3051 			kproc_suspend_check(td->td_proc);
3052 			mtx_lock(&sync_mtx);
3053 		}
3054 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
3055 		if (syncer_state != SYNCER_RUNNING &&
3056 		    starttime != time_uptime) {
3057 			if (first_printf) {
3058 				printf("\nSyncing disks, vnodes remaining... ");
3059 				first_printf = 0;
3060 			}
3061 			printf("%d ", net_worklist_len);
3062 		}
3063 		starttime = time_uptime;
3064 
3065 		/*
3066 		 * Push files whose dirty time has expired.  Be careful
3067 		 * of interrupt race on slp queue.
3068 		 *
3069 		 * Skip over empty worklist slots when shutting down.
3070 		 */
3071 		do {
3072 			slp = &syncer_workitem_pending[syncer_delayno];
3073 			syncer_delayno += 1;
3074 			if (syncer_delayno == syncer_maxdelay)
3075 				syncer_delayno = 0;
3076 			next = &syncer_workitem_pending[syncer_delayno];
3077 			/*
3078 			 * If the worklist has wrapped since the
3079 			 * it was emptied of all but syncer vnodes,
3080 			 * switch to the FINAL_DELAY state and run
3081 			 * for one more second.
3082 			 */
3083 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
3084 			    net_worklist_len == 0 &&
3085 			    last_work_seen == syncer_delayno) {
3086 				syncer_state = SYNCER_FINAL_DELAY;
3087 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
3088 			}
3089 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
3090 		    syncer_worklist_len > 0);
3091 
3092 		/*
3093 		 * Keep track of the last time there was anything
3094 		 * on the worklist other than syncer vnodes.
3095 		 * Return to the SHUTTING_DOWN state if any
3096 		 * new work appears.
3097 		 */
3098 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
3099 			last_work_seen = syncer_delayno;
3100 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
3101 			syncer_state = SYNCER_SHUTTING_DOWN;
3102 		while (!LIST_EMPTY(slp)) {
3103 			error = sync_vnode(slp, &bo, td);
3104 			if (error == 1) {
3105 				LIST_REMOVE(bo, bo_synclist);
3106 				LIST_INSERT_HEAD(next, bo, bo_synclist);
3107 				continue;
3108 			}
3109 
3110 			if (first_printf == 0) {
3111 				/*
3112 				 * Drop the sync mutex, because some watchdog
3113 				 * drivers need to sleep while patting
3114 				 */
3115 				mtx_unlock(&sync_mtx);
3116 				wdog_kern_pat(WD_LASTVAL);
3117 				mtx_lock(&sync_mtx);
3118 			}
3119 		}
3120 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
3121 			syncer_final_iter--;
3122 		/*
3123 		 * The variable rushjob allows the kernel to speed up the
3124 		 * processing of the filesystem syncer process. A rushjob
3125 		 * value of N tells the filesystem syncer to process the next
3126 		 * N seconds worth of work on its queue ASAP. Currently rushjob
3127 		 * is used by the soft update code to speed up the filesystem
3128 		 * syncer process when the incore state is getting so far
3129 		 * ahead of the disk that the kernel memory pool is being
3130 		 * threatened with exhaustion.
3131 		 */
3132 		if (rushjob > 0) {
3133 			rushjob -= 1;
3134 			continue;
3135 		}
3136 		/*
3137 		 * Just sleep for a short period of time between
3138 		 * iterations when shutting down to allow some I/O
3139 		 * to happen.
3140 		 *
3141 		 * If it has taken us less than a second to process the
3142 		 * current work, then wait. Otherwise start right over
3143 		 * again. We can still lose time if any single round
3144 		 * takes more than two seconds, but it does not really
3145 		 * matter as we are just trying to generally pace the
3146 		 * filesystem activity.
3147 		 */
3148 		if (syncer_state != SYNCER_RUNNING ||
3149 		    time_uptime == starttime) {
3150 			thread_lock(td);
3151 			sched_prio(td, PPAUSE);
3152 			thread_unlock(td);
3153 		}
3154 		if (syncer_state != SYNCER_RUNNING)
3155 			cv_timedwait(&sync_wakeup, &sync_mtx,
3156 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
3157 		else if (time_uptime == starttime)
3158 			cv_timedwait(&sync_wakeup, &sync_mtx, hz);
3159 	}
3160 }
3161 
3162 /*
3163  * Request the syncer daemon to speed up its work.
3164  * We never push it to speed up more than half of its
3165  * normal turn time, otherwise it could take over the cpu.
3166  */
3167 int
3168 speedup_syncer(void)
3169 {
3170 	int ret = 0;
3171 
3172 	mtx_lock(&sync_mtx);
3173 	if (rushjob < syncdelay / 2) {
3174 		rushjob += 1;
3175 		stat_rush_requests += 1;
3176 		ret = 1;
3177 	}
3178 	mtx_unlock(&sync_mtx);
3179 	cv_broadcast(&sync_wakeup);
3180 	return (ret);
3181 }
3182 
3183 /*
3184  * Tell the syncer to speed up its work and run though its work
3185  * list several times, then tell it to shut down.
3186  */
3187 static void
3188 syncer_shutdown(void *arg, int howto)
3189 {
3190 
3191 	if (howto & RB_NOSYNC)
3192 		return;
3193 	mtx_lock(&sync_mtx);
3194 	syncer_state = SYNCER_SHUTTING_DOWN;
3195 	rushjob = 0;
3196 	mtx_unlock(&sync_mtx);
3197 	cv_broadcast(&sync_wakeup);
3198 	kproc_shutdown(arg, howto);
3199 }
3200 
3201 void
3202 syncer_suspend(void)
3203 {
3204 
3205 	syncer_shutdown(updateproc, 0);
3206 }
3207 
3208 void
3209 syncer_resume(void)
3210 {
3211 
3212 	mtx_lock(&sync_mtx);
3213 	first_printf = 1;
3214 	syncer_state = SYNCER_RUNNING;
3215 	mtx_unlock(&sync_mtx);
3216 	cv_broadcast(&sync_wakeup);
3217 	kproc_resume(updateproc);
3218 }
3219 
3220 /*
3221  * Move the buffer between the clean and dirty lists of its vnode.
3222  */
3223 void
3224 reassignbuf(struct buf *bp)
3225 {
3226 	struct vnode *vp;
3227 	struct bufobj *bo;
3228 	int delay;
3229 #ifdef INVARIANTS
3230 	struct bufv *bv;
3231 #endif
3232 
3233 	vp = bp->b_vp;
3234 	bo = bp->b_bufobj;
3235 
3236 	KASSERT((bp->b_flags & B_PAGING) == 0,
3237 	    ("%s: cannot reassign paging buffer %p", __func__, bp));
3238 
3239 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
3240 	    bp, bp->b_vp, bp->b_flags);
3241 
3242 	BO_LOCK(bo);
3243 	if ((bo->bo_flag & BO_NONSTERILE) == 0) {
3244 		/*
3245 		 * Coordinate with getblk's unlocked lookup.  Make
3246 		 * BO_NONSTERILE visible before the first reassignbuf produces
3247 		 * any side effect.  This could be outside the bo lock if we
3248 		 * used a separate atomic flag field.
3249 		 */
3250 		bo->bo_flag |= BO_NONSTERILE;
3251 		atomic_thread_fence_rel();
3252 	}
3253 	buf_vlist_remove(bp);
3254 
3255 	/*
3256 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
3257 	 * of clean buffers.
3258 	 */
3259 	if (bp->b_flags & B_DELWRI) {
3260 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
3261 			switch (vp->v_type) {
3262 			case VDIR:
3263 				delay = dirdelay;
3264 				break;
3265 			case VCHR:
3266 				delay = metadelay;
3267 				break;
3268 			default:
3269 				delay = filedelay;
3270 			}
3271 			vn_syncer_add_to_worklist(bo, delay);
3272 		}
3273 		buf_vlist_add(bp, bo, BX_VNDIRTY);
3274 	} else {
3275 		buf_vlist_add(bp, bo, BX_VNCLEAN);
3276 
3277 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
3278 			mtx_lock(&sync_mtx);
3279 			LIST_REMOVE(bo, bo_synclist);
3280 			syncer_worklist_len--;
3281 			mtx_unlock(&sync_mtx);
3282 			bo->bo_flag &= ~BO_ONWORKLST;
3283 		}
3284 	}
3285 #ifdef INVARIANTS
3286 	bv = &bo->bo_clean;
3287 	bp = TAILQ_FIRST(&bv->bv_hd);
3288 	KASSERT(bp == NULL || bp->b_bufobj == bo,
3289 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3290 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
3291 	KASSERT(bp == NULL || bp->b_bufobj == bo,
3292 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3293 	bv = &bo->bo_dirty;
3294 	bp = TAILQ_FIRST(&bv->bv_hd);
3295 	KASSERT(bp == NULL || bp->b_bufobj == bo,
3296 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3297 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
3298 	KASSERT(bp == NULL || bp->b_bufobj == bo,
3299 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
3300 #endif
3301 	BO_UNLOCK(bo);
3302 }
3303 
3304 static void
3305 v_init_counters(struct vnode *vp)
3306 {
3307 
3308 	VNASSERT(vp->v_type == VNON && vp->v_data == NULL && vp->v_iflag == 0,
3309 	    vp, ("%s called for an initialized vnode", __FUNCTION__));
3310 	ASSERT_VI_UNLOCKED(vp, __FUNCTION__);
3311 
3312 	refcount_init(&vp->v_holdcnt, 1);
3313 	refcount_init(&vp->v_usecount, 1);
3314 }
3315 
3316 /*
3317  * Get a usecount on a vnode.
3318  *
3319  * vget and vget_finish may fail to lock the vnode if they lose a race against
3320  * it being doomed. LK_RETRY can be passed in flags to lock it anyway.
3321  *
3322  * Consumers which don't guarantee liveness of the vnode can use SMR to
3323  * try to get a reference. Note this operation can fail since the vnode
3324  * may be awaiting getting freed by the time they get to it.
3325  */
3326 enum vgetstate
3327 vget_prep_smr(struct vnode *vp)
3328 {
3329 	enum vgetstate vs;
3330 
3331 	VFS_SMR_ASSERT_ENTERED();
3332 
3333 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3334 		vs = VGET_USECOUNT;
3335 	} else {
3336 		if (vhold_smr(vp))
3337 			vs = VGET_HOLDCNT;
3338 		else
3339 			vs = VGET_NONE;
3340 	}
3341 	return (vs);
3342 }
3343 
3344 enum vgetstate
3345 vget_prep(struct vnode *vp)
3346 {
3347 	enum vgetstate vs;
3348 
3349 	if (refcount_acquire_if_not_zero(&vp->v_usecount)) {
3350 		vs = VGET_USECOUNT;
3351 	} else {
3352 		vhold(vp);
3353 		vs = VGET_HOLDCNT;
3354 	}
3355 	return (vs);
3356 }
3357 
3358 void
3359 vget_abort(struct vnode *vp, enum vgetstate vs)
3360 {
3361 
3362 	switch (vs) {
3363 	case VGET_USECOUNT:
3364 		vrele(vp);
3365 		goto out_ok;
3366 	case VGET_HOLDCNT:
3367 		vdrop(vp);
3368 		goto out_ok;
3369 	case VGET_NONE:
3370 		break;
3371 	}
3372 
3373 	__assert_unreachable();
3374 
3375 	/*
3376 	 * This is a goto label should the cases above have more in common than
3377 	 * just the 'return' statement.
3378 	 */
3379 out_ok:
3380 	return;
3381 }
3382 
3383 int
3384 vget(struct vnode *vp, int flags)
3385 {
3386 	enum vgetstate vs;
3387 
3388 	vs = vget_prep(vp);
3389 	return (vget_finish(vp, flags, vs));
3390 }
3391 
3392 int
3393 vget_finish(struct vnode *vp, int flags, enum vgetstate vs)
3394 {
3395 	int error;
3396 
3397 	if ((flags & LK_INTERLOCK) != 0)
3398 		ASSERT_VI_LOCKED(vp, __func__);
3399 	else
3400 		ASSERT_VI_UNLOCKED(vp, __func__);
3401 	VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3402 	VNPASS(vp->v_holdcnt > 0, vp);
3403 	VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3404 
3405 	error = vn_lock(vp, flags);
3406 	if (__predict_false(error != 0)) {
3407 		vget_abort(vp, vs);
3408 		CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
3409 		    vp);
3410 		return (error);
3411 	}
3412 
3413 	vget_finish_ref(vp, vs);
3414 	return (0);
3415 }
3416 
3417 void
3418 vget_finish_ref(struct vnode *vp, enum vgetstate vs)
3419 {
3420 	int old;
3421 
3422 	VNPASS(vs == VGET_HOLDCNT || vs == VGET_USECOUNT, vp);
3423 	VNPASS(vp->v_holdcnt > 0, vp);
3424 	VNPASS(vs == VGET_HOLDCNT || vp->v_usecount > 0, vp);
3425 
3426 	if (vs == VGET_USECOUNT)
3427 		return;
3428 
3429 	/*
3430 	 * We hold the vnode. If the usecount is 0 it will be utilized to keep
3431 	 * the vnode around. Otherwise someone else lended their hold count and
3432 	 * we have to drop ours.
3433 	 */
3434 	old = atomic_fetchadd_int(&vp->v_usecount, 1);
3435 	VNASSERT(old >= 0, vp, ("%s: wrong use count %d", __func__, old));
3436 	if (old != 0) {
3437 #ifdef INVARIANTS
3438 		old = atomic_fetchadd_int(&vp->v_holdcnt, -1);
3439 		VNASSERT(old > 1, vp, ("%s: wrong hold count %d", __func__, old));
3440 #else
3441 		refcount_release(&vp->v_holdcnt);
3442 #endif
3443 	}
3444 }
3445 
3446 void
3447 vref(struct vnode *vp)
3448 {
3449 	enum vgetstate vs;
3450 
3451 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3452 	vs = vget_prep(vp);
3453 	vget_finish_ref(vp, vs);
3454 }
3455 
3456 void
3457 vrefact(struct vnode *vp)
3458 {
3459 	int old __diagused;
3460 
3461 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3462 	old = refcount_acquire(&vp->v_usecount);
3463 	VNASSERT(old > 0, vp, ("%s: wrong use count %d", __func__, old));
3464 }
3465 
3466 void
3467 vlazy(struct vnode *vp)
3468 {
3469 	struct mount *mp;
3470 
3471 	VNASSERT(vp->v_holdcnt > 0, vp, ("%s: vnode not held", __func__));
3472 
3473 	if ((vp->v_mflag & VMP_LAZYLIST) != 0)
3474 		return;
3475 	/*
3476 	 * We may get here for inactive routines after the vnode got doomed.
3477 	 */
3478 	if (VN_IS_DOOMED(vp))
3479 		return;
3480 	mp = vp->v_mount;
3481 	mtx_lock(&mp->mnt_listmtx);
3482 	if ((vp->v_mflag & VMP_LAZYLIST) == 0) {
3483 		vp->v_mflag |= VMP_LAZYLIST;
3484 		TAILQ_INSERT_TAIL(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3485 		mp->mnt_lazyvnodelistsize++;
3486 	}
3487 	mtx_unlock(&mp->mnt_listmtx);
3488 }
3489 
3490 static void
3491 vunlazy(struct vnode *vp)
3492 {
3493 	struct mount *mp;
3494 
3495 	ASSERT_VI_LOCKED(vp, __func__);
3496 	VNPASS(!VN_IS_DOOMED(vp), vp);
3497 
3498 	mp = vp->v_mount;
3499 	mtx_lock(&mp->mnt_listmtx);
3500 	VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3501 	/*
3502 	 * Don't remove the vnode from the lazy list if another thread
3503 	 * has increased the hold count. It may have re-enqueued the
3504 	 * vnode to the lazy list and is now responsible for its
3505 	 * removal.
3506 	 */
3507 	if (vp->v_holdcnt == 0) {
3508 		vp->v_mflag &= ~VMP_LAZYLIST;
3509 		TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3510 		mp->mnt_lazyvnodelistsize--;
3511 	}
3512 	mtx_unlock(&mp->mnt_listmtx);
3513 }
3514 
3515 /*
3516  * This routine is only meant to be called from vgonel prior to dooming
3517  * the vnode.
3518  */
3519 static void
3520 vunlazy_gone(struct vnode *vp)
3521 {
3522 	struct mount *mp;
3523 
3524 	ASSERT_VOP_ELOCKED(vp, __func__);
3525 	ASSERT_VI_LOCKED(vp, __func__);
3526 	VNPASS(!VN_IS_DOOMED(vp), vp);
3527 
3528 	if (vp->v_mflag & VMP_LAZYLIST) {
3529 		mp = vp->v_mount;
3530 		mtx_lock(&mp->mnt_listmtx);
3531 		VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
3532 		vp->v_mflag &= ~VMP_LAZYLIST;
3533 		TAILQ_REMOVE(&mp->mnt_lazyvnodelist, vp, v_lazylist);
3534 		mp->mnt_lazyvnodelistsize--;
3535 		mtx_unlock(&mp->mnt_listmtx);
3536 	}
3537 }
3538 
3539 static void
3540 vdefer_inactive(struct vnode *vp)
3541 {
3542 
3543 	ASSERT_VI_LOCKED(vp, __func__);
3544 	VNPASS(vp->v_holdcnt > 0, vp);
3545 	if (VN_IS_DOOMED(vp)) {
3546 		vdropl(vp);
3547 		return;
3548 	}
3549 	if (vp->v_iflag & VI_DEFINACT) {
3550 		VNPASS(vp->v_holdcnt > 1, vp);
3551 		vdropl(vp);
3552 		return;
3553 	}
3554 	if (vp->v_usecount > 0) {
3555 		vp->v_iflag &= ~VI_OWEINACT;
3556 		vdropl(vp);
3557 		return;
3558 	}
3559 	vlazy(vp);
3560 	vp->v_iflag |= VI_DEFINACT;
3561 	VI_UNLOCK(vp);
3562 	atomic_add_long(&deferred_inact, 1);
3563 }
3564 
3565 static void
3566 vdefer_inactive_unlocked(struct vnode *vp)
3567 {
3568 
3569 	VI_LOCK(vp);
3570 	if ((vp->v_iflag & VI_OWEINACT) == 0) {
3571 		vdropl(vp);
3572 		return;
3573 	}
3574 	vdefer_inactive(vp);
3575 }
3576 
3577 enum vput_op { VRELE, VPUT, VUNREF };
3578 
3579 /*
3580  * Handle ->v_usecount transitioning to 0.
3581  *
3582  * By releasing the last usecount we take ownership of the hold count which
3583  * provides liveness of the vnode, meaning we have to vdrop.
3584  *
3585  * For all vnodes we may need to perform inactive processing. It requires an
3586  * exclusive lock on the vnode, while it is legal to call here with only a
3587  * shared lock (or no locks). If locking the vnode in an expected manner fails,
3588  * inactive processing gets deferred to the syncer.
3589  */
3590 static void
3591 vput_final(struct vnode *vp, enum vput_op func)
3592 {
3593 	int error;
3594 	bool want_unlock;
3595 
3596 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3597 	VNPASS(vp->v_holdcnt > 0, vp);
3598 
3599 	VI_LOCK(vp);
3600 
3601 	/*
3602 	 * By the time we got here someone else might have transitioned
3603 	 * the count back to > 0.
3604 	 */
3605 	if (vp->v_usecount > 0)
3606 		goto out;
3607 
3608 	/*
3609 	 * If the vnode is doomed vgone already performed inactive processing
3610 	 * (if needed).
3611 	 */
3612 	if (VN_IS_DOOMED(vp))
3613 		goto out;
3614 
3615 	if (__predict_true(VOP_NEED_INACTIVE(vp) == 0))
3616 		goto out;
3617 
3618 	if (vp->v_iflag & VI_DOINGINACT)
3619 		goto out;
3620 
3621 	/*
3622 	 * Locking operations here will drop the interlock and possibly the
3623 	 * vnode lock, opening a window where the vnode can get doomed all the
3624 	 * while ->v_usecount is 0. Set VI_OWEINACT to let vgone know to
3625 	 * perform inactive.
3626 	 */
3627 	vp->v_iflag |= VI_OWEINACT;
3628 	want_unlock = false;
3629 	error = 0;
3630 	switch (func) {
3631 	case VRELE:
3632 		switch (VOP_ISLOCKED(vp)) {
3633 		case LK_EXCLUSIVE:
3634 			break;
3635 		case LK_EXCLOTHER:
3636 		case 0:
3637 			want_unlock = true;
3638 			error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
3639 			VI_LOCK(vp);
3640 			break;
3641 		default:
3642 			/*
3643 			 * The lock has at least one sharer, but we have no way
3644 			 * to conclude whether this is us. Play it safe and
3645 			 * defer processing.
3646 			 */
3647 			error = EAGAIN;
3648 			break;
3649 		}
3650 		break;
3651 	case VPUT:
3652 		want_unlock = true;
3653 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3654 			error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK |
3655 			    LK_NOWAIT);
3656 			VI_LOCK(vp);
3657 		}
3658 		break;
3659 	case VUNREF:
3660 		if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
3661 			error = VOP_LOCK(vp, LK_TRYUPGRADE | LK_INTERLOCK);
3662 			VI_LOCK(vp);
3663 		}
3664 		break;
3665 	}
3666 	if (error != 0) {
3667 		vdefer_inactive(vp);
3668 		return;
3669 	}
3670 	if (func == VUNREF) {
3671 		VNASSERT((vp->v_vflag & VV_UNREF) == 0, vp,
3672 		    ("recursive vunref"));
3673 		vp->v_vflag |= VV_UNREF;
3674 	}
3675 	for (;;) {
3676 		error = vinactive(vp);
3677 		if (want_unlock)
3678 			VOP_UNLOCK(vp);
3679 		if (error != ERELOOKUP || !want_unlock)
3680 			break;
3681 		VOP_LOCK(vp, LK_EXCLUSIVE);
3682 	}
3683 	if (func == VUNREF)
3684 		vp->v_vflag &= ~VV_UNREF;
3685 	vdropl(vp);
3686 	return;
3687 out:
3688 	if (func == VPUT)
3689 		VOP_UNLOCK(vp);
3690 	vdropl(vp);
3691 }
3692 
3693 /*
3694  * Decrement ->v_usecount for a vnode.
3695  *
3696  * Releasing the last use count requires additional processing, see vput_final
3697  * above for details.
3698  *
3699  * Comment above each variant denotes lock state on entry and exit.
3700  */
3701 
3702 /*
3703  * in: any
3704  * out: same as passed in
3705  */
3706 void
3707 vrele(struct vnode *vp)
3708 {
3709 
3710 	ASSERT_VI_UNLOCKED(vp, __func__);
3711 	if (!refcount_release(&vp->v_usecount))
3712 		return;
3713 	vput_final(vp, VRELE);
3714 }
3715 
3716 /*
3717  * in: locked
3718  * out: unlocked
3719  */
3720 void
3721 vput(struct vnode *vp)
3722 {
3723 
3724 	ASSERT_VOP_LOCKED(vp, __func__);
3725 	ASSERT_VI_UNLOCKED(vp, __func__);
3726 	if (!refcount_release(&vp->v_usecount)) {
3727 		VOP_UNLOCK(vp);
3728 		return;
3729 	}
3730 	vput_final(vp, VPUT);
3731 }
3732 
3733 /*
3734  * in: locked
3735  * out: locked
3736  */
3737 void
3738 vunref(struct vnode *vp)
3739 {
3740 
3741 	ASSERT_VOP_LOCKED(vp, __func__);
3742 	ASSERT_VI_UNLOCKED(vp, __func__);
3743 	if (!refcount_release(&vp->v_usecount))
3744 		return;
3745 	vput_final(vp, VUNREF);
3746 }
3747 
3748 void
3749 vhold(struct vnode *vp)
3750 {
3751 	int old;
3752 
3753 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3754 	old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3755 	VNASSERT(old >= 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3756 	    ("%s: wrong hold count %d", __func__, old));
3757 	if (old == 0)
3758 		vfs_freevnodes_dec();
3759 }
3760 
3761 void
3762 vholdnz(struct vnode *vp)
3763 {
3764 
3765 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3766 #ifdef INVARIANTS
3767 	int old = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3768 	VNASSERT(old > 0 && (old & VHOLD_ALL_FLAGS) == 0, vp,
3769 	    ("%s: wrong hold count %d", __func__, old));
3770 #else
3771 	atomic_add_int(&vp->v_holdcnt, 1);
3772 #endif
3773 }
3774 
3775 /*
3776  * Grab a hold count unless the vnode is freed.
3777  *
3778  * Only use this routine if vfs smr is the only protection you have against
3779  * freeing the vnode.
3780  *
3781  * The code loops trying to add a hold count as long as the VHOLD_NO_SMR flag
3782  * is not set.  After the flag is set the vnode becomes immutable to anyone but
3783  * the thread which managed to set the flag.
3784  *
3785  * It may be tempting to replace the loop with:
3786  * count = atomic_fetchadd_int(&vp->v_holdcnt, 1);
3787  * if (count & VHOLD_NO_SMR) {
3788  *     backpedal and error out;
3789  * }
3790  *
3791  * However, while this is more performant, it hinders debugging by eliminating
3792  * the previously mentioned invariant.
3793  */
3794 bool
3795 vhold_smr(struct vnode *vp)
3796 {
3797 	int count;
3798 
3799 	VFS_SMR_ASSERT_ENTERED();
3800 
3801 	count = atomic_load_int(&vp->v_holdcnt);
3802 	for (;;) {
3803 		if (count & VHOLD_NO_SMR) {
3804 			VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3805 			    ("non-zero hold count with flags %d\n", count));
3806 			return (false);
3807 		}
3808 		VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3809 		if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3810 			if (count == 0)
3811 				vfs_freevnodes_dec();
3812 			return (true);
3813 		}
3814 	}
3815 }
3816 
3817 /*
3818  * Hold a free vnode for recycling.
3819  *
3820  * Note: vnode_init references this comment.
3821  *
3822  * Attempts to recycle only need the global vnode list lock and have no use for
3823  * SMR.
3824  *
3825  * However, vnodes get inserted into the global list before they get fully
3826  * initialized and stay there until UMA decides to free the memory. This in
3827  * particular means the target can be found before it becomes usable and after
3828  * it becomes recycled. Picking up such vnodes is guarded with v_holdcnt set to
3829  * VHOLD_NO_SMR.
3830  *
3831  * Note: the vnode may gain more references after we transition the count 0->1.
3832  */
3833 static bool
3834 vhold_recycle_free(struct vnode *vp)
3835 {
3836 	int count;
3837 
3838 	mtx_assert(&vnode_list_mtx, MA_OWNED);
3839 
3840 	count = atomic_load_int(&vp->v_holdcnt);
3841 	for (;;) {
3842 		if (count & VHOLD_NO_SMR) {
3843 			VNASSERT((count & ~VHOLD_NO_SMR) == 0, vp,
3844 			    ("non-zero hold count with flags %d\n", count));
3845 			return (false);
3846 		}
3847 		VNASSERT(count >= 0, vp, ("invalid hold count %d\n", count));
3848 		if (count > 0) {
3849 			return (false);
3850 		}
3851 		if (atomic_fcmpset_int(&vp->v_holdcnt, &count, count + 1)) {
3852 			vfs_freevnodes_dec();
3853 			return (true);
3854 		}
3855 	}
3856 }
3857 
3858 static void __noinline
3859 vdbatch_process(struct vdbatch *vd)
3860 {
3861 	struct vnode *vp;
3862 	int i;
3863 
3864 	mtx_assert(&vd->lock, MA_OWNED);
3865 	MPASS(curthread->td_pinned > 0);
3866 	MPASS(vd->index == VDBATCH_SIZE);
3867 
3868 	/*
3869 	 * Attempt to requeue the passed batch, but give up easily.
3870 	 *
3871 	 * Despite batching the mechanism is prone to transient *significant*
3872 	 * lock contention, where vnode_list_mtx becomes the primary bottleneck
3873 	 * if multiple CPUs get here (one real-world example is highly parallel
3874 	 * do-nothing make , which will stat *tons* of vnodes). Since it is
3875 	 * quasi-LRU (read: not that great even if fully honoured) provide an
3876 	 * option to just dodge the problem. Parties which don't like it are
3877 	 * welcome to implement something better.
3878 	 */
3879 	if (vnode_can_skip_requeue) {
3880 		if (!mtx_trylock(&vnode_list_mtx)) {
3881 			counter_u64_add(vnode_skipped_requeues, 1);
3882 			critical_enter();
3883 			for (i = 0; i < VDBATCH_SIZE; i++) {
3884 				vp = vd->tab[i];
3885 				vd->tab[i] = NULL;
3886 				MPASS(vp->v_dbatchcpu != NOCPU);
3887 				vp->v_dbatchcpu = NOCPU;
3888 			}
3889 			vd->index = 0;
3890 			critical_exit();
3891 			return;
3892 
3893 		}
3894 		/* fallthrough to locked processing */
3895 	} else {
3896 		mtx_lock(&vnode_list_mtx);
3897 	}
3898 
3899 	mtx_assert(&vnode_list_mtx, MA_OWNED);
3900 	critical_enter();
3901 	for (i = 0; i < VDBATCH_SIZE; i++) {
3902 		vp = vd->tab[i];
3903 		vd->tab[i] = NULL;
3904 		TAILQ_REMOVE(&vnode_list, vp, v_vnodelist);
3905 		TAILQ_INSERT_TAIL(&vnode_list, vp, v_vnodelist);
3906 		MPASS(vp->v_dbatchcpu != NOCPU);
3907 		vp->v_dbatchcpu = NOCPU;
3908 	}
3909 	mtx_unlock(&vnode_list_mtx);
3910 	vd->index = 0;
3911 	critical_exit();
3912 }
3913 
3914 static void
3915 vdbatch_enqueue(struct vnode *vp)
3916 {
3917 	struct vdbatch *vd;
3918 
3919 	ASSERT_VI_LOCKED(vp, __func__);
3920 	VNPASS(!VN_IS_DOOMED(vp), vp);
3921 
3922 	if (vp->v_dbatchcpu != NOCPU) {
3923 		VI_UNLOCK(vp);
3924 		return;
3925 	}
3926 
3927 	sched_pin();
3928 	vd = DPCPU_PTR(vd);
3929 	mtx_lock(&vd->lock);
3930 	MPASS(vd->index < VDBATCH_SIZE);
3931 	MPASS(vd->tab[vd->index] == NULL);
3932 	/*
3933 	 * A hack: we depend on being pinned so that we know what to put in
3934 	 * ->v_dbatchcpu.
3935 	 */
3936 	vp->v_dbatchcpu = curcpu;
3937 	vd->tab[vd->index] = vp;
3938 	vd->index++;
3939 	VI_UNLOCK(vp);
3940 	if (vd->index == VDBATCH_SIZE)
3941 		vdbatch_process(vd);
3942 	mtx_unlock(&vd->lock);
3943 	sched_unpin();
3944 }
3945 
3946 /*
3947  * This routine must only be called for vnodes which are about to be
3948  * deallocated. Supporting dequeue for arbitrary vndoes would require
3949  * validating that the locked batch matches.
3950  */
3951 static void
3952 vdbatch_dequeue(struct vnode *vp)
3953 {
3954 	struct vdbatch *vd;
3955 	int i;
3956 	short cpu;
3957 
3958 	VNPASS(vp->v_type == VBAD || vp->v_type == VNON, vp);
3959 
3960 	cpu = vp->v_dbatchcpu;
3961 	if (cpu == NOCPU)
3962 		return;
3963 
3964 	vd = DPCPU_ID_PTR(cpu, vd);
3965 	mtx_lock(&vd->lock);
3966 	for (i = 0; i < vd->index; i++) {
3967 		if (vd->tab[i] != vp)
3968 			continue;
3969 		vp->v_dbatchcpu = NOCPU;
3970 		vd->index--;
3971 		vd->tab[i] = vd->tab[vd->index];
3972 		vd->tab[vd->index] = NULL;
3973 		break;
3974 	}
3975 	mtx_unlock(&vd->lock);
3976 	/*
3977 	 * Either we dequeued the vnode above or the target CPU beat us to it.
3978 	 */
3979 	MPASS(vp->v_dbatchcpu == NOCPU);
3980 }
3981 
3982 /*
3983  * Drop the hold count of the vnode.
3984  *
3985  * It will only get freed if this is the last hold *and* it has been vgone'd.
3986  *
3987  * Because the vnode vm object keeps a hold reference on the vnode if
3988  * there is at least one resident non-cached page, the vnode cannot
3989  * leave the active list without the page cleanup done.
3990  */
3991 static void __noinline
3992 vdropl_final(struct vnode *vp)
3993 {
3994 
3995 	ASSERT_VI_LOCKED(vp, __func__);
3996 	VNPASS(VN_IS_DOOMED(vp), vp);
3997 	/*
3998 	 * Set the VHOLD_NO_SMR flag.
3999 	 *
4000 	 * We may be racing against vhold_smr. If they win we can just pretend
4001 	 * we never got this far, they will vdrop later.
4002 	 */
4003 	if (__predict_false(!atomic_cmpset_int(&vp->v_holdcnt, 0, VHOLD_NO_SMR))) {
4004 		vfs_freevnodes_inc();
4005 		VI_UNLOCK(vp);
4006 		/*
4007 		 * We lost the aforementioned race. Any subsequent access is
4008 		 * invalid as they might have managed to vdropl on their own.
4009 		 */
4010 		return;
4011 	}
4012 	/*
4013 	 * Don't bump freevnodes as this one is going away.
4014 	 */
4015 	freevnode(vp);
4016 }
4017 
4018 void
4019 vdrop(struct vnode *vp)
4020 {
4021 
4022 	ASSERT_VI_UNLOCKED(vp, __func__);
4023 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4024 	if (refcount_release_if_not_last(&vp->v_holdcnt))
4025 		return;
4026 	VI_LOCK(vp);
4027 	vdropl(vp);
4028 }
4029 
4030 static __always_inline void
4031 vdropl_impl(struct vnode *vp, bool enqueue)
4032 {
4033 
4034 	ASSERT_VI_LOCKED(vp, __func__);
4035 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4036 	if (!refcount_release(&vp->v_holdcnt)) {
4037 		VI_UNLOCK(vp);
4038 		return;
4039 	}
4040 	VNPASS((vp->v_iflag & VI_OWEINACT) == 0, vp);
4041 	VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
4042 	if (VN_IS_DOOMED(vp)) {
4043 		vdropl_final(vp);
4044 		return;
4045 	}
4046 
4047 	vfs_freevnodes_inc();
4048 	if (vp->v_mflag & VMP_LAZYLIST) {
4049 		vunlazy(vp);
4050 	}
4051 
4052 	if (!enqueue) {
4053 		VI_UNLOCK(vp);
4054 		return;
4055 	}
4056 
4057 	/*
4058 	 * Also unlocks the interlock. We can't assert on it as we
4059 	 * released our hold and by now the vnode might have been
4060 	 * freed.
4061 	 */
4062 	vdbatch_enqueue(vp);
4063 }
4064 
4065 void
4066 vdropl(struct vnode *vp)
4067 {
4068 
4069 	vdropl_impl(vp, true);
4070 }
4071 
4072 /*
4073  * vdrop a vnode when recycling
4074  *
4075  * This is a special case routine only to be used when recycling, differs from
4076  * regular vdrop by not requeieing the vnode on LRU.
4077  *
4078  * Consider a case where vtryrecycle continuously fails with all vnodes (due to
4079  * e.g., frozen writes on the filesystem), filling the batch and causing it to
4080  * be requeued. Then vnlru will end up revisiting the same vnodes. This is a
4081  * loop which can last for as long as writes are frozen.
4082  */
4083 static void
4084 vdropl_recycle(struct vnode *vp)
4085 {
4086 
4087 	vdropl_impl(vp, false);
4088 }
4089 
4090 static void
4091 vdrop_recycle(struct vnode *vp)
4092 {
4093 
4094 	VI_LOCK(vp);
4095 	vdropl_recycle(vp);
4096 }
4097 
4098 /*
4099  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
4100  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
4101  */
4102 static int
4103 vinactivef(struct vnode *vp)
4104 {
4105 	int error;
4106 
4107 	ASSERT_VOP_ELOCKED(vp, "vinactive");
4108 	ASSERT_VI_LOCKED(vp, "vinactive");
4109 	VNPASS((vp->v_iflag & VI_DOINGINACT) == 0, vp);
4110 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4111 	vp->v_iflag |= VI_DOINGINACT;
4112 	vp->v_iflag &= ~VI_OWEINACT;
4113 	VI_UNLOCK(vp);
4114 
4115 	/*
4116 	 * Before moving off the active list, we must be sure that any
4117 	 * modified pages are converted into the vnode's dirty
4118 	 * buffers, since these will no longer be checked once the
4119 	 * vnode is on the inactive list.
4120 	 *
4121 	 * The write-out of the dirty pages is asynchronous.  At the
4122 	 * point that VOP_INACTIVE() is called, there could still be
4123 	 * pending I/O and dirty pages in the object.
4124 	 */
4125 	if ((vp->v_vflag & VV_NOSYNC) == 0)
4126 		vnode_pager_clean_async(vp);
4127 
4128 	error = VOP_INACTIVE(vp);
4129 	VI_LOCK(vp);
4130 	VNPASS(vp->v_iflag & VI_DOINGINACT, vp);
4131 	vp->v_iflag &= ~VI_DOINGINACT;
4132 	return (error);
4133 }
4134 
4135 int
4136 vinactive(struct vnode *vp)
4137 {
4138 
4139 	ASSERT_VOP_ELOCKED(vp, "vinactive");
4140 	ASSERT_VI_LOCKED(vp, "vinactive");
4141 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4142 
4143 	if ((vp->v_iflag & VI_OWEINACT) == 0)
4144 		return (0);
4145 	if (vp->v_iflag & VI_DOINGINACT)
4146 		return (0);
4147 	if (vp->v_usecount > 0) {
4148 		vp->v_iflag &= ~VI_OWEINACT;
4149 		return (0);
4150 	}
4151 	return (vinactivef(vp));
4152 }
4153 
4154 /*
4155  * Remove any vnodes in the vnode table belonging to mount point mp.
4156  *
4157  * If FORCECLOSE is not specified, there should not be any active ones,
4158  * return error if any are found (nb: this is a user error, not a
4159  * system error). If FORCECLOSE is specified, detach any active vnodes
4160  * that are found.
4161  *
4162  * If WRITECLOSE is set, only flush out regular file vnodes open for
4163  * writing.
4164  *
4165  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
4166  *
4167  * `rootrefs' specifies the base reference count for the root vnode
4168  * of this filesystem. The root vnode is considered busy if its
4169  * v_usecount exceeds this value. On a successful return, vflush(, td)
4170  * will call vrele() on the root vnode exactly rootrefs times.
4171  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
4172  * be zero.
4173  */
4174 #ifdef DIAGNOSTIC
4175 static int busyprt = 0;		/* print out busy vnodes */
4176 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "Print out busy vnodes");
4177 #endif
4178 
4179 int
4180 vflush(struct mount *mp, int rootrefs, int flags, struct thread *td)
4181 {
4182 	struct vnode *vp, *mvp, *rootvp = NULL;
4183 	struct vattr vattr;
4184 	int busy = 0, error;
4185 
4186 	CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
4187 	    rootrefs, flags);
4188 	if (rootrefs > 0) {
4189 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
4190 		    ("vflush: bad args"));
4191 		/*
4192 		 * Get the filesystem root vnode. We can vput() it
4193 		 * immediately, since with rootrefs > 0, it won't go away.
4194 		 */
4195 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
4196 			CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
4197 			    __func__, error);
4198 			return (error);
4199 		}
4200 		vput(rootvp);
4201 	}
4202 loop:
4203 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
4204 		vholdl(vp);
4205 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
4206 		if (error) {
4207 			vdrop(vp);
4208 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
4209 			goto loop;
4210 		}
4211 		/*
4212 		 * Skip over a vnodes marked VV_SYSTEM.
4213 		 */
4214 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
4215 			VOP_UNLOCK(vp);
4216 			vdrop(vp);
4217 			continue;
4218 		}
4219 		/*
4220 		 * If WRITECLOSE is set, flush out unlinked but still open
4221 		 * files (even if open only for reading) and regular file
4222 		 * vnodes open for writing.
4223 		 */
4224 		if (flags & WRITECLOSE) {
4225 			vnode_pager_clean_async(vp);
4226 			do {
4227 				error = VOP_FSYNC(vp, MNT_WAIT, td);
4228 			} while (error == ERELOOKUP);
4229 			if (error != 0) {
4230 				VOP_UNLOCK(vp);
4231 				vdrop(vp);
4232 				MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
4233 				return (error);
4234 			}
4235 			error = VOP_GETATTR(vp, &vattr, td->td_ucred);
4236 			VI_LOCK(vp);
4237 
4238 			if ((vp->v_type == VNON ||
4239 			    (error == 0 && vattr.va_nlink > 0)) &&
4240 			    (vp->v_writecount <= 0 || vp->v_type != VREG)) {
4241 				VOP_UNLOCK(vp);
4242 				vdropl(vp);
4243 				continue;
4244 			}
4245 		} else
4246 			VI_LOCK(vp);
4247 		/*
4248 		 * With v_usecount == 0, all we need to do is clear out the
4249 		 * vnode data structures and we are done.
4250 		 *
4251 		 * If FORCECLOSE is set, forcibly close the vnode.
4252 		 */
4253 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
4254 			vgonel(vp);
4255 		} else {
4256 			busy++;
4257 #ifdef DIAGNOSTIC
4258 			if (busyprt)
4259 				vn_printf(vp, "vflush: busy vnode ");
4260 #endif
4261 		}
4262 		VOP_UNLOCK(vp);
4263 		vdropl(vp);
4264 	}
4265 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
4266 		/*
4267 		 * If just the root vnode is busy, and if its refcount
4268 		 * is equal to `rootrefs', then go ahead and kill it.
4269 		 */
4270 		VI_LOCK(rootvp);
4271 		KASSERT(busy > 0, ("vflush: not busy"));
4272 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
4273 		    ("vflush: usecount %d < rootrefs %d",
4274 		     rootvp->v_usecount, rootrefs));
4275 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
4276 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
4277 			vgone(rootvp);
4278 			VOP_UNLOCK(rootvp);
4279 			busy = 0;
4280 		} else
4281 			VI_UNLOCK(rootvp);
4282 	}
4283 	if (busy) {
4284 		CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
4285 		    busy);
4286 		return (EBUSY);
4287 	}
4288 	for (; rootrefs > 0; rootrefs--)
4289 		vrele(rootvp);
4290 	return (0);
4291 }
4292 
4293 /*
4294  * Recycle an unused vnode.
4295  */
4296 int
4297 vrecycle(struct vnode *vp)
4298 {
4299 	int recycled;
4300 
4301 	VI_LOCK(vp);
4302 	recycled = vrecyclel(vp);
4303 	VI_UNLOCK(vp);
4304 	return (recycled);
4305 }
4306 
4307 /*
4308  * vrecycle, with the vp interlock held.
4309  */
4310 int
4311 vrecyclel(struct vnode *vp)
4312 {
4313 	int recycled;
4314 
4315 	ASSERT_VOP_ELOCKED(vp, __func__);
4316 	ASSERT_VI_LOCKED(vp, __func__);
4317 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4318 	recycled = 0;
4319 	if (vp->v_usecount == 0) {
4320 		recycled = 1;
4321 		vgonel(vp);
4322 	}
4323 	return (recycled);
4324 }
4325 
4326 /*
4327  * Eliminate all activity associated with a vnode
4328  * in preparation for reuse.
4329  */
4330 void
4331 vgone(struct vnode *vp)
4332 {
4333 	VI_LOCK(vp);
4334 	vgonel(vp);
4335 	VI_UNLOCK(vp);
4336 }
4337 
4338 /*
4339  * Notify upper mounts about reclaimed or unlinked vnode.
4340  */
4341 void
4342 vfs_notify_upper(struct vnode *vp, enum vfs_notify_upper_type event)
4343 {
4344 	struct mount *mp;
4345 	struct mount_upper_node *ump;
4346 
4347 	mp = atomic_load_ptr(&vp->v_mount);
4348 	if (mp == NULL)
4349 		return;
4350 	if (TAILQ_EMPTY(&mp->mnt_notify))
4351 		return;
4352 
4353 	MNT_ILOCK(mp);
4354 	mp->mnt_upper_pending++;
4355 	KASSERT(mp->mnt_upper_pending > 0,
4356 	    ("%s: mnt_upper_pending %d", __func__, mp->mnt_upper_pending));
4357 	TAILQ_FOREACH(ump, &mp->mnt_notify, mnt_upper_link) {
4358 		MNT_IUNLOCK(mp);
4359 		switch (event) {
4360 		case VFS_NOTIFY_UPPER_RECLAIM:
4361 			VFS_RECLAIM_LOWERVP(ump->mp, vp);
4362 			break;
4363 		case VFS_NOTIFY_UPPER_UNLINK:
4364 			VFS_UNLINK_LOWERVP(ump->mp, vp);
4365 			break;
4366 		}
4367 		MNT_ILOCK(mp);
4368 	}
4369 	mp->mnt_upper_pending--;
4370 	if ((mp->mnt_kern_flag & MNTK_UPPER_WAITER) != 0 &&
4371 	    mp->mnt_upper_pending == 0) {
4372 		mp->mnt_kern_flag &= ~MNTK_UPPER_WAITER;
4373 		wakeup(&mp->mnt_uppers);
4374 	}
4375 	MNT_IUNLOCK(mp);
4376 }
4377 
4378 /*
4379  * vgone, with the vp interlock held.
4380  */
4381 static void
4382 vgonel(struct vnode *vp)
4383 {
4384 	struct thread *td;
4385 	struct mount *mp;
4386 	vm_object_t object;
4387 	bool active, doinginact, oweinact;
4388 
4389 	ASSERT_VOP_ELOCKED(vp, "vgonel");
4390 	ASSERT_VI_LOCKED(vp, "vgonel");
4391 	VNASSERT(vp->v_holdcnt, vp,
4392 	    ("vgonel: vp %p has no reference.", vp));
4393 	CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
4394 	td = curthread;
4395 
4396 	/*
4397 	 * Don't vgonel if we're already doomed.
4398 	 */
4399 	if (VN_IS_DOOMED(vp)) {
4400 		VNPASS(vn_get_state(vp) == VSTATE_DESTROYING || \
4401 		    vn_get_state(vp) == VSTATE_DEAD, vp);
4402 		return;
4403 	}
4404 	/*
4405 	 * Paired with freevnode.
4406 	 */
4407 	vn_seqc_write_begin_locked(vp);
4408 	vunlazy_gone(vp);
4409 	vn_irflag_set_locked(vp, VIRF_DOOMED);
4410 	vn_set_state(vp, VSTATE_DESTROYING);
4411 
4412 	/*
4413 	 * Check to see if the vnode is in use.  If so, we have to
4414 	 * call VOP_CLOSE() and VOP_INACTIVE().
4415 	 *
4416 	 * It could be that VOP_INACTIVE() requested reclamation, in
4417 	 * which case we should avoid recursion, so check
4418 	 * VI_DOINGINACT.  This is not precise but good enough.
4419 	 */
4420 	active = vp->v_usecount > 0;
4421 	oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4422 	doinginact = (vp->v_iflag & VI_DOINGINACT) != 0;
4423 
4424 	/*
4425 	 * If we need to do inactive VI_OWEINACT will be set.
4426 	 */
4427 	if (vp->v_iflag & VI_DEFINACT) {
4428 		VNASSERT(vp->v_holdcnt > 1, vp, ("lost hold count"));
4429 		vp->v_iflag &= ~VI_DEFINACT;
4430 		vdropl(vp);
4431 	} else {
4432 		VNASSERT(vp->v_holdcnt > 0, vp, ("vnode without hold count"));
4433 		VI_UNLOCK(vp);
4434 	}
4435 	cache_purge_vgone(vp);
4436 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_RECLAIM);
4437 
4438 	/*
4439 	 * If purging an active vnode, it must be closed and
4440 	 * deactivated before being reclaimed.
4441 	 */
4442 	if (active)
4443 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
4444 	if (!doinginact) {
4445 		do {
4446 			if (oweinact || active) {
4447 				VI_LOCK(vp);
4448 				vinactivef(vp);
4449 				oweinact = (vp->v_iflag & VI_OWEINACT) != 0;
4450 				VI_UNLOCK(vp);
4451 			}
4452 		} while (oweinact);
4453 	}
4454 	if (vp->v_type == VSOCK)
4455 		vfs_unp_reclaim(vp);
4456 
4457 	/*
4458 	 * Clean out any buffers associated with the vnode.
4459 	 * If the flush fails, just toss the buffers.
4460 	 */
4461 	mp = NULL;
4462 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
4463 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
4464 	if (vinvalbuf(vp, V_SAVE, 0, 0) != 0) {
4465 		while (vinvalbuf(vp, 0, 0, 0) != 0)
4466 			;
4467 	}
4468 
4469 	BO_LOCK(&vp->v_bufobj);
4470 	KASSERT(TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd) &&
4471 	    vp->v_bufobj.bo_dirty.bv_cnt == 0 &&
4472 	    TAILQ_EMPTY(&vp->v_bufobj.bo_clean.bv_hd) &&
4473 	    vp->v_bufobj.bo_clean.bv_cnt == 0,
4474 	    ("vp %p bufobj not invalidated", vp));
4475 
4476 	/*
4477 	 * For VMIO bufobj, BO_DEAD is set later, or in
4478 	 * vm_object_terminate() after the object's page queue is
4479 	 * flushed.
4480 	 */
4481 	object = vp->v_bufobj.bo_object;
4482 	if (object == NULL)
4483 		vp->v_bufobj.bo_flag |= BO_DEAD;
4484 	BO_UNLOCK(&vp->v_bufobj);
4485 
4486 	/*
4487 	 * Handle the VM part.  Tmpfs handles v_object on its own (the
4488 	 * OBJT_VNODE check).  Nullfs or other bypassing filesystems
4489 	 * should not touch the object borrowed from the lower vnode
4490 	 * (the handle check).
4491 	 */
4492 	if (object != NULL && object->type == OBJT_VNODE &&
4493 	    object->handle == vp)
4494 		vnode_destroy_vobject(vp);
4495 
4496 	/*
4497 	 * Reclaim the vnode.
4498 	 */
4499 	if (VOP_RECLAIM(vp))
4500 		panic("vgone: cannot reclaim");
4501 	if (mp != NULL)
4502 		vn_finished_secondary_write(mp);
4503 	VNASSERT(vp->v_object == NULL, vp,
4504 	    ("vop_reclaim left v_object vp=%p", vp));
4505 	/*
4506 	 * Clear the advisory locks and wake up waiting threads.
4507 	 */
4508 	if (vp->v_lockf != NULL) {
4509 		(void)VOP_ADVLOCKPURGE(vp);
4510 		vp->v_lockf = NULL;
4511 	}
4512 	/*
4513 	 * Delete from old mount point vnode list.
4514 	 */
4515 	if (vp->v_mount == NULL) {
4516 		VI_LOCK(vp);
4517 	} else {
4518 		delmntque(vp);
4519 		ASSERT_VI_LOCKED(vp, "vgonel 2");
4520 	}
4521 	/*
4522 	 * Done with purge, reset to the standard lock and invalidate
4523 	 * the vnode.
4524 	 *
4525 	 * FIXME: this is buggy for vnode ops with custom locking primitives.
4526 	 *
4527 	 * vget used to be gated with a special flag serializing it against vgone,
4528 	 * which got lost in the process of SMP-ifying the VFS layer.
4529 	 *
4530 	 * Suppose a custom locking routine references ->v_data.
4531 	 *
4532 	 * Since now it is possible to start executing it as vgone is
4533 	 * progressing, this very well may crash as ->v_data gets invalidated
4534 	 * and memory used to back it is freed.
4535 	 */
4536 	vp->v_vnlock = &vp->v_lock;
4537 	vp->v_op = &dead_vnodeops;
4538 	vp->v_type = VBAD;
4539 	vn_set_state(vp, VSTATE_DEAD);
4540 }
4541 
4542 /*
4543  * Print out a description of a vnode.
4544  */
4545 static const char *const vtypename[] = {
4546 	[VNON] = "VNON",
4547 	[VREG] = "VREG",
4548 	[VDIR] = "VDIR",
4549 	[VBLK] = "VBLK",
4550 	[VCHR] = "VCHR",
4551 	[VLNK] = "VLNK",
4552 	[VSOCK] = "VSOCK",
4553 	[VFIFO] = "VFIFO",
4554 	[VBAD] = "VBAD",
4555 	[VMARKER] = "VMARKER",
4556 };
4557 _Static_assert(nitems(vtypename) == VLASTTYPE + 1,
4558     "vnode type name not added to vtypename");
4559 
4560 static const char *const vstatename[] = {
4561 	[VSTATE_UNINITIALIZED] = "VSTATE_UNINITIALIZED",
4562 	[VSTATE_CONSTRUCTED] = "VSTATE_CONSTRUCTED",
4563 	[VSTATE_DESTROYING] = "VSTATE_DESTROYING",
4564 	[VSTATE_DEAD] = "VSTATE_DEAD",
4565 };
4566 _Static_assert(nitems(vstatename) == VLASTSTATE + 1,
4567     "vnode state name not added to vstatename");
4568 
4569 _Static_assert((VHOLD_ALL_FLAGS & ~VHOLD_NO_SMR) == 0,
4570     "new hold count flag not added to vn_printf");
4571 
4572 void
4573 vn_printf(struct vnode *vp, const char *fmt, ...)
4574 {
4575 	va_list ap;
4576 	char buf[256], buf2[16];
4577 	u_long flags;
4578 	u_int holdcnt;
4579 	short irflag;
4580 
4581 	va_start(ap, fmt);
4582 	vprintf(fmt, ap);
4583 	va_end(ap);
4584 	printf("%p: ", (void *)vp);
4585 	printf("type %s state %s op %p\n", vtypename[vp->v_type],
4586 	    vstatename[vp->v_state], vp->v_op);
4587 	holdcnt = atomic_load_int(&vp->v_holdcnt);
4588 	printf("    usecount %d, writecount %d, refcount %d seqc users %d",
4589 	    vp->v_usecount, vp->v_writecount, holdcnt & ~VHOLD_ALL_FLAGS,
4590 	    vp->v_seqc_users);
4591 	switch (vp->v_type) {
4592 	case VDIR:
4593 		printf(" mountedhere %p\n", vp->v_mountedhere);
4594 		break;
4595 	case VCHR:
4596 		printf(" rdev %p\n", vp->v_rdev);
4597 		break;
4598 	case VSOCK:
4599 		printf(" socket %p\n", vp->v_unpcb);
4600 		break;
4601 	case VFIFO:
4602 		printf(" fifoinfo %p\n", vp->v_fifoinfo);
4603 		break;
4604 	default:
4605 		printf("\n");
4606 		break;
4607 	}
4608 	buf[0] = '\0';
4609 	buf[1] = '\0';
4610 	if (holdcnt & VHOLD_NO_SMR)
4611 		strlcat(buf, "|VHOLD_NO_SMR", sizeof(buf));
4612 	printf("    hold count flags (%s)\n", buf + 1);
4613 
4614 	buf[0] = '\0';
4615 	buf[1] = '\0';
4616 	irflag = vn_irflag_read(vp);
4617 	if (irflag & VIRF_DOOMED)
4618 		strlcat(buf, "|VIRF_DOOMED", sizeof(buf));
4619 	if (irflag & VIRF_PGREAD)
4620 		strlcat(buf, "|VIRF_PGREAD", sizeof(buf));
4621 	if (irflag & VIRF_MOUNTPOINT)
4622 		strlcat(buf, "|VIRF_MOUNTPOINT", sizeof(buf));
4623 	if (irflag & VIRF_TEXT_REF)
4624 		strlcat(buf, "|VIRF_TEXT_REF", sizeof(buf));
4625 	flags = irflag & ~(VIRF_DOOMED | VIRF_PGREAD | VIRF_MOUNTPOINT | VIRF_TEXT_REF);
4626 	if (flags != 0) {
4627 		snprintf(buf2, sizeof(buf2), "|VIRF(0x%lx)", flags);
4628 		strlcat(buf, buf2, sizeof(buf));
4629 	}
4630 	if (vp->v_vflag & VV_ROOT)
4631 		strlcat(buf, "|VV_ROOT", sizeof(buf));
4632 	if (vp->v_vflag & VV_ISTTY)
4633 		strlcat(buf, "|VV_ISTTY", sizeof(buf));
4634 	if (vp->v_vflag & VV_NOSYNC)
4635 		strlcat(buf, "|VV_NOSYNC", sizeof(buf));
4636 	if (vp->v_vflag & VV_ETERNALDEV)
4637 		strlcat(buf, "|VV_ETERNALDEV", sizeof(buf));
4638 	if (vp->v_vflag & VV_CACHEDLABEL)
4639 		strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
4640 	if (vp->v_vflag & VV_VMSIZEVNLOCK)
4641 		strlcat(buf, "|VV_VMSIZEVNLOCK", sizeof(buf));
4642 	if (vp->v_vflag & VV_COPYONWRITE)
4643 		strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
4644 	if (vp->v_vflag & VV_SYSTEM)
4645 		strlcat(buf, "|VV_SYSTEM", sizeof(buf));
4646 	if (vp->v_vflag & VV_PROCDEP)
4647 		strlcat(buf, "|VV_PROCDEP", sizeof(buf));
4648 	if (vp->v_vflag & VV_DELETED)
4649 		strlcat(buf, "|VV_DELETED", sizeof(buf));
4650 	if (vp->v_vflag & VV_MD)
4651 		strlcat(buf, "|VV_MD", sizeof(buf));
4652 	if (vp->v_vflag & VV_FORCEINSMQ)
4653 		strlcat(buf, "|VV_FORCEINSMQ", sizeof(buf));
4654 	if (vp->v_vflag & VV_READLINK)
4655 		strlcat(buf, "|VV_READLINK", sizeof(buf));
4656 	flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC | VV_ETERNALDEV |
4657 	    VV_CACHEDLABEL | VV_VMSIZEVNLOCK | VV_COPYONWRITE | VV_SYSTEM |
4658 	    VV_PROCDEP | VV_DELETED | VV_MD | VV_FORCEINSMQ | VV_READLINK);
4659 	if (flags != 0) {
4660 		snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
4661 		strlcat(buf, buf2, sizeof(buf));
4662 	}
4663 	if (vp->v_iflag & VI_MOUNT)
4664 		strlcat(buf, "|VI_MOUNT", sizeof(buf));
4665 	if (vp->v_iflag & VI_DOINGINACT)
4666 		strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
4667 	if (vp->v_iflag & VI_OWEINACT)
4668 		strlcat(buf, "|VI_OWEINACT", sizeof(buf));
4669 	if (vp->v_iflag & VI_DEFINACT)
4670 		strlcat(buf, "|VI_DEFINACT", sizeof(buf));
4671 	if (vp->v_iflag & VI_FOPENING)
4672 		strlcat(buf, "|VI_FOPENING", sizeof(buf));
4673 	flags = vp->v_iflag & ~(VI_MOUNT | VI_DOINGINACT |
4674 	    VI_OWEINACT | VI_DEFINACT | VI_FOPENING);
4675 	if (flags != 0) {
4676 		snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
4677 		strlcat(buf, buf2, sizeof(buf));
4678 	}
4679 	if (vp->v_mflag & VMP_LAZYLIST)
4680 		strlcat(buf, "|VMP_LAZYLIST", sizeof(buf));
4681 	flags = vp->v_mflag & ~(VMP_LAZYLIST);
4682 	if (flags != 0) {
4683 		snprintf(buf2, sizeof(buf2), "|VMP(0x%lx)", flags);
4684 		strlcat(buf, buf2, sizeof(buf));
4685 	}
4686 	printf("    flags (%s)", buf + 1);
4687 	if (mtx_owned(VI_MTX(vp)))
4688 		printf(" VI_LOCKed");
4689 	printf("\n");
4690 	if (vp->v_object != NULL)
4691 		printf("    v_object %p ref %d pages %d "
4692 		    "cleanbuf %d dirtybuf %d\n",
4693 		    vp->v_object, vp->v_object->ref_count,
4694 		    vp->v_object->resident_page_count,
4695 		    vp->v_bufobj.bo_clean.bv_cnt,
4696 		    vp->v_bufobj.bo_dirty.bv_cnt);
4697 	printf("    ");
4698 	lockmgr_printinfo(vp->v_vnlock);
4699 	if (vp->v_data != NULL)
4700 		VOP_PRINT(vp);
4701 }
4702 
4703 #ifdef DDB
4704 /*
4705  * List all of the locked vnodes in the system.
4706  * Called when debugging the kernel.
4707  */
4708 DB_SHOW_COMMAND_FLAGS(lockedvnods, lockedvnodes, DB_CMD_MEMSAFE)
4709 {
4710 	struct mount *mp;
4711 	struct vnode *vp;
4712 
4713 	/*
4714 	 * Note: because this is DDB, we can't obey the locking semantics
4715 	 * for these structures, which means we could catch an inconsistent
4716 	 * state and dereference a nasty pointer.  Not much to be done
4717 	 * about that.
4718 	 */
4719 	db_printf("Locked vnodes\n");
4720 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4721 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4722 			if (vp->v_type != VMARKER && VOP_ISLOCKED(vp))
4723 				vn_printf(vp, "vnode ");
4724 		}
4725 	}
4726 }
4727 
4728 /*
4729  * Show details about the given vnode.
4730  */
4731 DB_SHOW_COMMAND(vnode, db_show_vnode)
4732 {
4733 	struct vnode *vp;
4734 
4735 	if (!have_addr)
4736 		return;
4737 	vp = (struct vnode *)addr;
4738 	vn_printf(vp, "vnode ");
4739 }
4740 
4741 /*
4742  * Show details about the given mount point.
4743  */
4744 DB_SHOW_COMMAND(mount, db_show_mount)
4745 {
4746 	struct mount *mp;
4747 	struct vfsopt *opt;
4748 	struct statfs *sp;
4749 	struct vnode *vp;
4750 	char buf[512];
4751 	uint64_t mflags;
4752 	u_int flags;
4753 
4754 	if (!have_addr) {
4755 		/* No address given, print short info about all mount points. */
4756 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4757 			db_printf("%p %s on %s (%s)\n", mp,
4758 			    mp->mnt_stat.f_mntfromname,
4759 			    mp->mnt_stat.f_mntonname,
4760 			    mp->mnt_stat.f_fstypename);
4761 			if (db_pager_quit)
4762 				break;
4763 		}
4764 		db_printf("\nMore info: show mount <addr>\n");
4765 		return;
4766 	}
4767 
4768 	mp = (struct mount *)addr;
4769 	db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
4770 	    mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
4771 
4772 	buf[0] = '\0';
4773 	mflags = mp->mnt_flag;
4774 #define	MNT_FLAG(flag)	do {						\
4775 	if (mflags & (flag)) {						\
4776 		if (buf[0] != '\0')					\
4777 			strlcat(buf, ", ", sizeof(buf));		\
4778 		strlcat(buf, (#flag) + 4, sizeof(buf));			\
4779 		mflags &= ~(flag);					\
4780 	}								\
4781 } while (0)
4782 	MNT_FLAG(MNT_RDONLY);
4783 	MNT_FLAG(MNT_SYNCHRONOUS);
4784 	MNT_FLAG(MNT_NOEXEC);
4785 	MNT_FLAG(MNT_NOSUID);
4786 	MNT_FLAG(MNT_NFS4ACLS);
4787 	MNT_FLAG(MNT_UNION);
4788 	MNT_FLAG(MNT_ASYNC);
4789 	MNT_FLAG(MNT_SUIDDIR);
4790 	MNT_FLAG(MNT_SOFTDEP);
4791 	MNT_FLAG(MNT_NOSYMFOLLOW);
4792 	MNT_FLAG(MNT_GJOURNAL);
4793 	MNT_FLAG(MNT_MULTILABEL);
4794 	MNT_FLAG(MNT_ACLS);
4795 	MNT_FLAG(MNT_NOATIME);
4796 	MNT_FLAG(MNT_NOCLUSTERR);
4797 	MNT_FLAG(MNT_NOCLUSTERW);
4798 	MNT_FLAG(MNT_SUJ);
4799 	MNT_FLAG(MNT_EXRDONLY);
4800 	MNT_FLAG(MNT_EXPORTED);
4801 	MNT_FLAG(MNT_DEFEXPORTED);
4802 	MNT_FLAG(MNT_EXPORTANON);
4803 	MNT_FLAG(MNT_EXKERB);
4804 	MNT_FLAG(MNT_EXPUBLIC);
4805 	MNT_FLAG(MNT_LOCAL);
4806 	MNT_FLAG(MNT_QUOTA);
4807 	MNT_FLAG(MNT_ROOTFS);
4808 	MNT_FLAG(MNT_USER);
4809 	MNT_FLAG(MNT_IGNORE);
4810 	MNT_FLAG(MNT_UPDATE);
4811 	MNT_FLAG(MNT_DELEXPORT);
4812 	MNT_FLAG(MNT_RELOAD);
4813 	MNT_FLAG(MNT_FORCE);
4814 	MNT_FLAG(MNT_SNAPSHOT);
4815 	MNT_FLAG(MNT_BYFSID);
4816 	MNT_FLAG(MNT_NAMEDATTR);
4817 #undef MNT_FLAG
4818 	if (mflags != 0) {
4819 		if (buf[0] != '\0')
4820 			strlcat(buf, ", ", sizeof(buf));
4821 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4822 		    "0x%016jx", mflags);
4823 	}
4824 	db_printf("    mnt_flag = %s\n", buf);
4825 
4826 	buf[0] = '\0';
4827 	flags = mp->mnt_kern_flag;
4828 #define	MNT_KERN_FLAG(flag)	do {					\
4829 	if (flags & (flag)) {						\
4830 		if (buf[0] != '\0')					\
4831 			strlcat(buf, ", ", sizeof(buf));		\
4832 		strlcat(buf, (#flag) + 5, sizeof(buf));			\
4833 		flags &= ~(flag);					\
4834 	}								\
4835 } while (0)
4836 	MNT_KERN_FLAG(MNTK_UNMOUNTF);
4837 	MNT_KERN_FLAG(MNTK_ASYNC);
4838 	MNT_KERN_FLAG(MNTK_SOFTDEP);
4839 	MNT_KERN_FLAG(MNTK_NOMSYNC);
4840 	MNT_KERN_FLAG(MNTK_DRAINING);
4841 	MNT_KERN_FLAG(MNTK_REFEXPIRE);
4842 	MNT_KERN_FLAG(MNTK_EXTENDED_SHARED);
4843 	MNT_KERN_FLAG(MNTK_SHARED_WRITES);
4844 	MNT_KERN_FLAG(MNTK_NO_IOPF);
4845 	MNT_KERN_FLAG(MNTK_RECURSE);
4846 	MNT_KERN_FLAG(MNTK_UPPER_WAITER);
4847 	MNT_KERN_FLAG(MNTK_UNLOCKED_INSMNTQUE);
4848 	MNT_KERN_FLAG(MNTK_USES_BCACHE);
4849 	MNT_KERN_FLAG(MNTK_VMSETSIZE_BUG);
4850 	MNT_KERN_FLAG(MNTK_FPLOOKUP);
4851 	MNT_KERN_FLAG(MNTK_TASKQUEUE_WAITER);
4852 	MNT_KERN_FLAG(MNTK_NOASYNC);
4853 	MNT_KERN_FLAG(MNTK_UNMOUNT);
4854 	MNT_KERN_FLAG(MNTK_MWAIT);
4855 	MNT_KERN_FLAG(MNTK_SUSPEND);
4856 	MNT_KERN_FLAG(MNTK_SUSPEND2);
4857 	MNT_KERN_FLAG(MNTK_SUSPENDED);
4858 	MNT_KERN_FLAG(MNTK_NULL_NOCACHE);
4859 	MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
4860 #undef MNT_KERN_FLAG
4861 	if (flags != 0) {
4862 		if (buf[0] != '\0')
4863 			strlcat(buf, ", ", sizeof(buf));
4864 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
4865 		    "0x%08x", flags);
4866 	}
4867 	db_printf("    mnt_kern_flag = %s\n", buf);
4868 
4869 	db_printf("    mnt_opt = ");
4870 	opt = TAILQ_FIRST(mp->mnt_opt);
4871 	if (opt != NULL) {
4872 		db_printf("%s", opt->name);
4873 		opt = TAILQ_NEXT(opt, link);
4874 		while (opt != NULL) {
4875 			db_printf(", %s", opt->name);
4876 			opt = TAILQ_NEXT(opt, link);
4877 		}
4878 	}
4879 	db_printf("\n");
4880 
4881 	sp = &mp->mnt_stat;
4882 	db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
4883 	    "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
4884 	    "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
4885 	    "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
4886 	    (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
4887 	    (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
4888 	    (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
4889 	    (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
4890 	    (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
4891 	    (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
4892 	    (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
4893 	    (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
4894 
4895 	db_printf("    mnt_cred = { uid=%u ruid=%u",
4896 	    (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
4897 	if (jailed(mp->mnt_cred))
4898 		db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
4899 	db_printf(" }\n");
4900 	db_printf("    mnt_ref = %d (with %d in the struct)\n",
4901 	    vfs_mount_fetch_counter(mp, MNT_COUNT_REF), mp->mnt_ref);
4902 	db_printf("    mnt_gen = %d\n", mp->mnt_gen);
4903 	db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
4904 	db_printf("    mnt_lazyvnodelistsize = %d\n",
4905 	    mp->mnt_lazyvnodelistsize);
4906 	db_printf("    mnt_writeopcount = %d (with %d in the struct)\n",
4907 	    vfs_mount_fetch_counter(mp, MNT_COUNT_WRITEOPCOUNT), mp->mnt_writeopcount);
4908 	db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
4909 	db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
4910 	db_printf("    mnt_lockref = %d (with %d in the struct)\n",
4911 	    vfs_mount_fetch_counter(mp, MNT_COUNT_LOCKREF), mp->mnt_lockref);
4912 	db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
4913 	db_printf("    mnt_secondary_accwrites = %d\n",
4914 	    mp->mnt_secondary_accwrites);
4915 	db_printf("    mnt_gjprovider = %s\n",
4916 	    mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
4917 	db_printf("    mnt_vfs_ops = %d\n", mp->mnt_vfs_ops);
4918 
4919 	db_printf("\n\nList of active vnodes\n");
4920 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4921 		if (vp->v_type != VMARKER && vp->v_holdcnt > 0) {
4922 			vn_printf(vp, "vnode ");
4923 			if (db_pager_quit)
4924 				break;
4925 		}
4926 	}
4927 	db_printf("\n\nList of inactive vnodes\n");
4928 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
4929 		if (vp->v_type != VMARKER && vp->v_holdcnt == 0) {
4930 			vn_printf(vp, "vnode ");
4931 			if (db_pager_quit)
4932 				break;
4933 		}
4934 	}
4935 }
4936 #endif	/* DDB */
4937 
4938 /*
4939  * Fill in a struct xvfsconf based on a struct vfsconf.
4940  */
4941 static int
4942 vfsconf2x(struct sysctl_req *req, struct vfsconf *vfsp)
4943 {
4944 	struct xvfsconf xvfsp;
4945 
4946 	bzero(&xvfsp, sizeof(xvfsp));
4947 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4948 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
4949 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
4950 	xvfsp.vfc_flags = vfsp->vfc_flags;
4951 	/*
4952 	 * These are unused in userland, we keep them
4953 	 * to not break binary compatibility.
4954 	 */
4955 	xvfsp.vfc_vfsops = NULL;
4956 	xvfsp.vfc_next = NULL;
4957 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4958 }
4959 
4960 #ifdef COMPAT_FREEBSD32
4961 struct xvfsconf32 {
4962 	uint32_t	vfc_vfsops;
4963 	char		vfc_name[MFSNAMELEN];
4964 	int32_t		vfc_typenum;
4965 	int32_t		vfc_refcount;
4966 	int32_t		vfc_flags;
4967 	uint32_t	vfc_next;
4968 };
4969 
4970 static int
4971 vfsconf2x32(struct sysctl_req *req, struct vfsconf *vfsp)
4972 {
4973 	struct xvfsconf32 xvfsp;
4974 
4975 	bzero(&xvfsp, sizeof(xvfsp));
4976 	strcpy(xvfsp.vfc_name, vfsp->vfc_name);
4977 	xvfsp.vfc_typenum = vfsp->vfc_typenum;
4978 	xvfsp.vfc_refcount = vfsp->vfc_refcount;
4979 	xvfsp.vfc_flags = vfsp->vfc_flags;
4980 	return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
4981 }
4982 #endif
4983 
4984 /*
4985  * Top level filesystem related information gathering.
4986  */
4987 static int
4988 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
4989 {
4990 	struct vfsconf *vfsp;
4991 	int error;
4992 
4993 	error = 0;
4994 	vfsconf_slock();
4995 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
4996 #ifdef COMPAT_FREEBSD32
4997 		if (req->flags & SCTL_MASK32)
4998 			error = vfsconf2x32(req, vfsp);
4999 		else
5000 #endif
5001 			error = vfsconf2x(req, vfsp);
5002 		if (error)
5003 			break;
5004 	}
5005 	vfsconf_sunlock();
5006 	return (error);
5007 }
5008 
5009 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLTYPE_OPAQUE | CTLFLAG_RD |
5010     CTLFLAG_MPSAFE, NULL, 0, sysctl_vfs_conflist,
5011     "S,xvfsconf", "List of all configured filesystems");
5012 
5013 #ifndef BURN_BRIDGES
5014 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
5015 
5016 static int
5017 vfs_sysctl(SYSCTL_HANDLER_ARGS)
5018 {
5019 	int *name = (int *)arg1 - 1;	/* XXX */
5020 	u_int namelen = arg2 + 1;	/* XXX */
5021 	struct vfsconf *vfsp;
5022 
5023 	log(LOG_WARNING, "userland calling deprecated sysctl, "
5024 	    "please rebuild world\n");
5025 
5026 #if 1 || defined(COMPAT_PRELITE2)
5027 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
5028 	if (namelen == 1)
5029 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
5030 #endif
5031 
5032 	switch (name[1]) {
5033 	case VFS_MAXTYPENUM:
5034 		if (namelen != 2)
5035 			return (ENOTDIR);
5036 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
5037 	case VFS_CONF:
5038 		if (namelen != 3)
5039 			return (ENOTDIR);	/* overloaded */
5040 		vfsconf_slock();
5041 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
5042 			if (vfsp->vfc_typenum == name[2])
5043 				break;
5044 		}
5045 		vfsconf_sunlock();
5046 		if (vfsp == NULL)
5047 			return (EOPNOTSUPP);
5048 #ifdef COMPAT_FREEBSD32
5049 		if (req->flags & SCTL_MASK32)
5050 			return (vfsconf2x32(req, vfsp));
5051 		else
5052 #endif
5053 			return (vfsconf2x(req, vfsp));
5054 	}
5055 	return (EOPNOTSUPP);
5056 }
5057 
5058 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP |
5059     CTLFLAG_MPSAFE, vfs_sysctl,
5060     "Generic filesystem");
5061 
5062 #if 1 || defined(COMPAT_PRELITE2)
5063 
5064 static int
5065 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
5066 {
5067 	int error;
5068 	struct vfsconf *vfsp;
5069 	struct ovfsconf ovfs;
5070 
5071 	vfsconf_slock();
5072 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
5073 		bzero(&ovfs, sizeof(ovfs));
5074 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
5075 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
5076 		ovfs.vfc_index = vfsp->vfc_typenum;
5077 		ovfs.vfc_refcount = vfsp->vfc_refcount;
5078 		ovfs.vfc_flags = vfsp->vfc_flags;
5079 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
5080 		if (error != 0) {
5081 			vfsconf_sunlock();
5082 			return (error);
5083 		}
5084 	}
5085 	vfsconf_sunlock();
5086 	return (0);
5087 }
5088 
5089 #endif /* 1 || COMPAT_PRELITE2 */
5090 #endif /* !BURN_BRIDGES */
5091 
5092 static void
5093 unmount_or_warn(struct mount *mp)
5094 {
5095 	int error;
5096 
5097 	error = dounmount(mp, MNT_FORCE, curthread);
5098 	if (error != 0) {
5099 		printf("unmount of %s failed (", mp->mnt_stat.f_mntonname);
5100 		if (error == EBUSY)
5101 			printf("BUSY)\n");
5102 		else
5103 			printf("%d)\n", error);
5104 	}
5105 }
5106 
5107 /*
5108  * Unmount all filesystems. The list is traversed in reverse order
5109  * of mounting to avoid dependencies.
5110  */
5111 void
5112 vfs_unmountall(void)
5113 {
5114 	struct mount *mp, *tmp;
5115 
5116 	CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
5117 
5118 	/*
5119 	 * Since this only runs when rebooting, it is not interlocked.
5120 	 */
5121 	TAILQ_FOREACH_REVERSE_SAFE(mp, &mountlist, mntlist, mnt_list, tmp) {
5122 		vfs_ref(mp);
5123 
5124 		/*
5125 		 * Forcibly unmounting "/dev" before "/" would prevent clean
5126 		 * unmount of the latter.
5127 		 */
5128 		if (mp == rootdevmp)
5129 			continue;
5130 
5131 		unmount_or_warn(mp);
5132 	}
5133 
5134 	if (rootdevmp != NULL)
5135 		unmount_or_warn(rootdevmp);
5136 }
5137 
5138 static void
5139 vfs_deferred_inactive(struct vnode *vp, int lkflags)
5140 {
5141 
5142 	ASSERT_VI_LOCKED(vp, __func__);
5143 	VNPASS((vp->v_iflag & VI_DEFINACT) == 0, vp);
5144 	if ((vp->v_iflag & VI_OWEINACT) == 0) {
5145 		vdropl(vp);
5146 		return;
5147 	}
5148 	if (vn_lock(vp, lkflags) == 0) {
5149 		VI_LOCK(vp);
5150 		vinactive(vp);
5151 		VOP_UNLOCK(vp);
5152 		vdropl(vp);
5153 		return;
5154 	}
5155 	vdefer_inactive_unlocked(vp);
5156 }
5157 
5158 static int
5159 vfs_periodic_inactive_filter(struct vnode *vp, void *arg)
5160 {
5161 
5162 	return (vp->v_iflag & VI_DEFINACT);
5163 }
5164 
5165 static void __noinline
5166 vfs_periodic_inactive(struct mount *mp, int flags)
5167 {
5168 	struct vnode *vp, *mvp;
5169 	int lkflags;
5170 
5171 	lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5172 	if (flags != MNT_WAIT)
5173 		lkflags |= LK_NOWAIT;
5174 
5175 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_inactive_filter, NULL) {
5176 		if ((vp->v_iflag & VI_DEFINACT) == 0) {
5177 			VI_UNLOCK(vp);
5178 			continue;
5179 		}
5180 		vp->v_iflag &= ~VI_DEFINACT;
5181 		vfs_deferred_inactive(vp, lkflags);
5182 	}
5183 }
5184 
5185 static inline bool
5186 vfs_want_msync(struct vnode *vp)
5187 {
5188 	struct vm_object *obj;
5189 
5190 	/*
5191 	 * This test may be performed without any locks held.
5192 	 * We rely on vm_object's type stability.
5193 	 */
5194 	if (vp->v_vflag & VV_NOSYNC)
5195 		return (false);
5196 	obj = vp->v_object;
5197 	return (obj != NULL && vm_object_mightbedirty(obj));
5198 }
5199 
5200 static int
5201 vfs_periodic_msync_inactive_filter(struct vnode *vp, void *arg __unused)
5202 {
5203 
5204 	if (vp->v_vflag & VV_NOSYNC)
5205 		return (false);
5206 	if (vp->v_iflag & VI_DEFINACT)
5207 		return (true);
5208 	return (vfs_want_msync(vp));
5209 }
5210 
5211 static void __noinline
5212 vfs_periodic_msync_inactive(struct mount *mp, int flags)
5213 {
5214 	struct vnode *vp, *mvp;
5215 	int lkflags;
5216 	bool seen_defer;
5217 
5218 	lkflags = LK_EXCLUSIVE | LK_INTERLOCK;
5219 	if (flags != MNT_WAIT)
5220 		lkflags |= LK_NOWAIT;
5221 
5222 	MNT_VNODE_FOREACH_LAZY(vp, mp, mvp, vfs_periodic_msync_inactive_filter, NULL) {
5223 		seen_defer = false;
5224 		if (vp->v_iflag & VI_DEFINACT) {
5225 			vp->v_iflag &= ~VI_DEFINACT;
5226 			seen_defer = true;
5227 		}
5228 		if (!vfs_want_msync(vp)) {
5229 			if (seen_defer)
5230 				vfs_deferred_inactive(vp, lkflags);
5231 			else
5232 				VI_UNLOCK(vp);
5233 			continue;
5234 		}
5235 		if (vget(vp, lkflags) == 0) {
5236 			if ((vp->v_vflag & VV_NOSYNC) == 0) {
5237 				if (flags == MNT_WAIT)
5238 					vnode_pager_clean_sync(vp);
5239 				else
5240 					vnode_pager_clean_async(vp);
5241 			}
5242 			vput(vp);
5243 			if (seen_defer)
5244 				vdrop(vp);
5245 		} else {
5246 			if (seen_defer)
5247 				vdefer_inactive_unlocked(vp);
5248 		}
5249 	}
5250 }
5251 
5252 void
5253 vfs_periodic(struct mount *mp, int flags)
5254 {
5255 
5256 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
5257 
5258 	if ((mp->mnt_kern_flag & MNTK_NOMSYNC) != 0)
5259 		vfs_periodic_inactive(mp, flags);
5260 	else
5261 		vfs_periodic_msync_inactive(mp, flags);
5262 }
5263 
5264 static void
5265 destroy_vpollinfo_free(struct vpollinfo *vi)
5266 {
5267 
5268 	knlist_destroy(&vi->vpi_selinfo.si_note);
5269 	mtx_destroy(&vi->vpi_lock);
5270 	free(vi, M_VNODEPOLL);
5271 }
5272 
5273 static void
5274 destroy_vpollinfo(struct vpollinfo *vi)
5275 {
5276 	KASSERT(TAILQ_EMPTY(&vi->vpi_inotify),
5277 	    ("%s: pollinfo %p has lingering watches", __func__, vi));
5278 	knlist_clear(&vi->vpi_selinfo.si_note, 1);
5279 	seldrain(&vi->vpi_selinfo);
5280 	destroy_vpollinfo_free(vi);
5281 }
5282 
5283 /*
5284  * Initialize per-vnode helper structure to hold poll-related state.
5285  */
5286 void
5287 v_addpollinfo(struct vnode *vp)
5288 {
5289 	struct vpollinfo *vi;
5290 
5291 	if (atomic_load_ptr(&vp->v_pollinfo) != NULL)
5292 		return;
5293 	vi = malloc(sizeof(*vi), M_VNODEPOLL, M_WAITOK | M_ZERO);
5294 	mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
5295 	knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
5296 	    vfs_knlunlock, vfs_knl_assert_lock);
5297 	TAILQ_INIT(&vi->vpi_inotify);
5298 	VI_LOCK(vp);
5299 	if (vp->v_pollinfo != NULL) {
5300 		VI_UNLOCK(vp);
5301 		destroy_vpollinfo_free(vi);
5302 		return;
5303 	}
5304 	vp->v_pollinfo = vi;
5305 	VI_UNLOCK(vp);
5306 }
5307 
5308 /*
5309  * Record a process's interest in events which might happen to
5310  * a vnode.  Because poll uses the historic select-style interface
5311  * internally, this routine serves as both the ``check for any
5312  * pending events'' and the ``record my interest in future events''
5313  * functions.  (These are done together, while the lock is held,
5314  * to avoid race conditions.)
5315  */
5316 int
5317 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
5318 {
5319 
5320 	v_addpollinfo(vp);
5321 	mtx_lock(&vp->v_pollinfo->vpi_lock);
5322 	if (vp->v_pollinfo->vpi_revents & events) {
5323 		/*
5324 		 * This leaves events we are not interested
5325 		 * in available for the other process which
5326 		 * which presumably had requested them
5327 		 * (otherwise they would never have been
5328 		 * recorded).
5329 		 */
5330 		events &= vp->v_pollinfo->vpi_revents;
5331 		vp->v_pollinfo->vpi_revents &= ~events;
5332 
5333 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
5334 		return (events);
5335 	}
5336 	vp->v_pollinfo->vpi_events |= events;
5337 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
5338 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
5339 	return (0);
5340 }
5341 
5342 /*
5343  * Routine to create and manage a filesystem syncer vnode.
5344  */
5345 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
5346 static int	sync_fsync(struct  vop_fsync_args *);
5347 static int	sync_inactive(struct  vop_inactive_args *);
5348 static int	sync_reclaim(struct  vop_reclaim_args *);
5349 
5350 static struct vop_vector sync_vnodeops = {
5351 	.vop_bypass =	VOP_EOPNOTSUPP,
5352 	.vop_close =	sync_close,
5353 	.vop_fsync =	sync_fsync,
5354 	.vop_getwritemount = vop_stdgetwritemount,
5355 	.vop_inactive =	sync_inactive,
5356 	.vop_need_inactive = vop_stdneed_inactive,
5357 	.vop_reclaim =	sync_reclaim,
5358 	.vop_lock1 =	vop_stdlock,
5359 	.vop_unlock =	vop_stdunlock,
5360 	.vop_islocked =	vop_stdislocked,
5361 	.vop_fplookup_vexec = VOP_EAGAIN,
5362 	.vop_fplookup_symlink = VOP_EAGAIN,
5363 };
5364 VFS_VOP_VECTOR_REGISTER(sync_vnodeops);
5365 
5366 /*
5367  * Create a new filesystem syncer vnode for the specified mount point.
5368  */
5369 void
5370 vfs_allocate_syncvnode(struct mount *mp)
5371 {
5372 	struct vnode *vp;
5373 	struct bufobj *bo;
5374 	static long start, incr, next;
5375 	int error;
5376 
5377 	/* Allocate a new vnode */
5378 	error = getnewvnode("syncer", mp, &sync_vnodeops, &vp);
5379 	if (error != 0)
5380 		panic("vfs_allocate_syncvnode: getnewvnode() failed");
5381 	vp->v_type = VNON;
5382 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5383 	vp->v_vflag |= VV_FORCEINSMQ;
5384 	error = insmntque1(vp, mp);
5385 	if (error != 0)
5386 		panic("vfs_allocate_syncvnode: insmntque() failed");
5387 	vp->v_vflag &= ~VV_FORCEINSMQ;
5388 	vn_set_state(vp, VSTATE_CONSTRUCTED);
5389 	VOP_UNLOCK(vp);
5390 	/*
5391 	 * Place the vnode onto the syncer worklist. We attempt to
5392 	 * scatter them about on the list so that they will go off
5393 	 * at evenly distributed times even if all the filesystems
5394 	 * are mounted at once.
5395 	 */
5396 	next += incr;
5397 	if (next == 0 || next > syncer_maxdelay) {
5398 		start /= 2;
5399 		incr /= 2;
5400 		if (start == 0) {
5401 			start = syncer_maxdelay / 2;
5402 			incr = syncer_maxdelay;
5403 		}
5404 		next = start;
5405 	}
5406 	bo = &vp->v_bufobj;
5407 	BO_LOCK(bo);
5408 	vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
5409 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
5410 	mtx_lock(&sync_mtx);
5411 	sync_vnode_count++;
5412 	if (mp->mnt_syncer == NULL) {
5413 		mp->mnt_syncer = vp;
5414 		vp = NULL;
5415 	}
5416 	mtx_unlock(&sync_mtx);
5417 	BO_UNLOCK(bo);
5418 	if (vp != NULL) {
5419 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
5420 		vgone(vp);
5421 		vput(vp);
5422 	}
5423 }
5424 
5425 void
5426 vfs_deallocate_syncvnode(struct mount *mp)
5427 {
5428 	struct vnode *vp;
5429 
5430 	mtx_lock(&sync_mtx);
5431 	vp = mp->mnt_syncer;
5432 	if (vp != NULL)
5433 		mp->mnt_syncer = NULL;
5434 	mtx_unlock(&sync_mtx);
5435 	if (vp != NULL)
5436 		vrele(vp);
5437 }
5438 
5439 /*
5440  * Do a lazy sync of the filesystem.
5441  */
5442 static int
5443 sync_fsync(struct vop_fsync_args *ap)
5444 {
5445 	struct vnode *syncvp = ap->a_vp;
5446 	struct mount *mp = syncvp->v_mount;
5447 	int error, save;
5448 	struct bufobj *bo;
5449 
5450 	/*
5451 	 * We only need to do something if this is a lazy evaluation.
5452 	 */
5453 	if (ap->a_waitfor != MNT_LAZY)
5454 		return (0);
5455 
5456 	/*
5457 	 * Move ourselves to the back of the sync list.
5458 	 */
5459 	bo = &syncvp->v_bufobj;
5460 	BO_LOCK(bo);
5461 	vn_syncer_add_to_worklist(bo, syncdelay);
5462 	BO_UNLOCK(bo);
5463 
5464 	/*
5465 	 * Walk the list of vnodes pushing all that are dirty and
5466 	 * not already on the sync list.
5467 	 */
5468 	if (vfs_busy(mp, MBF_NOWAIT) != 0)
5469 		return (0);
5470 	VOP_UNLOCK(syncvp);
5471 	save = curthread_pflags_set(TDP_SYNCIO);
5472 	/*
5473 	 * The filesystem at hand may be idle with free vnodes stored in the
5474 	 * batch.  Return them instead of letting them stay there indefinitely.
5475 	 */
5476 	vfs_periodic(mp, MNT_NOWAIT);
5477 	error = VFS_SYNC(mp, MNT_LAZY);
5478 	curthread_pflags_restore(save);
5479 	vn_lock(syncvp, LK_EXCLUSIVE | LK_RETRY);
5480 	vfs_unbusy(mp);
5481 	return (error);
5482 }
5483 
5484 /*
5485  * The syncer vnode is no referenced.
5486  */
5487 static int
5488 sync_inactive(struct vop_inactive_args *ap)
5489 {
5490 
5491 	vgone(ap->a_vp);
5492 	return (0);
5493 }
5494 
5495 /*
5496  * The syncer vnode is no longer needed and is being decommissioned.
5497  *
5498  * Modifications to the worklist must be protected by sync_mtx.
5499  */
5500 static int
5501 sync_reclaim(struct vop_reclaim_args *ap)
5502 {
5503 	struct vnode *vp = ap->a_vp;
5504 	struct bufobj *bo;
5505 
5506 	bo = &vp->v_bufobj;
5507 	BO_LOCK(bo);
5508 	mtx_lock(&sync_mtx);
5509 	if (vp->v_mount->mnt_syncer == vp)
5510 		vp->v_mount->mnt_syncer = NULL;
5511 	if (bo->bo_flag & BO_ONWORKLST) {
5512 		LIST_REMOVE(bo, bo_synclist);
5513 		syncer_worklist_len--;
5514 		sync_vnode_count--;
5515 		bo->bo_flag &= ~BO_ONWORKLST;
5516 	}
5517 	mtx_unlock(&sync_mtx);
5518 	BO_UNLOCK(bo);
5519 
5520 	return (0);
5521 }
5522 
5523 int
5524 vn_need_pageq_flush(struct vnode *vp)
5525 {
5526 	struct vm_object *obj;
5527 
5528 	obj = vp->v_object;
5529 	return (obj != NULL && (vp->v_vflag & VV_NOSYNC) == 0 &&
5530 	    vm_object_mightbedirty(obj));
5531 }
5532 
5533 /*
5534  * Check if vnode represents a disk device
5535  */
5536 bool
5537 vn_isdisk_error(struct vnode *vp, int *errp)
5538 {
5539 	int error;
5540 
5541 	if (vp->v_type != VCHR) {
5542 		error = ENOTBLK;
5543 		goto out;
5544 	}
5545 	error = 0;
5546 	dev_lock();
5547 	if (vp->v_rdev == NULL)
5548 		error = ENXIO;
5549 	else if (vp->v_rdev->si_devsw == NULL)
5550 		error = ENXIO;
5551 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
5552 		error = ENOTBLK;
5553 	dev_unlock();
5554 out:
5555 	*errp = error;
5556 	return (error == 0);
5557 }
5558 
5559 bool
5560 vn_isdisk(struct vnode *vp)
5561 {
5562 	int error;
5563 
5564 	return (vn_isdisk_error(vp, &error));
5565 }
5566 
5567 /*
5568  * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
5569  * the comment above cache_fplookup for details.
5570  */
5571 int
5572 vaccess_vexec_smr(mode_t file_mode, uid_t file_uid, gid_t file_gid, struct ucred *cred)
5573 {
5574 	int error;
5575 
5576 	VFS_SMR_ASSERT_ENTERED();
5577 
5578 	/* Check the owner. */
5579 	if (cred->cr_uid == file_uid) {
5580 		if (file_mode & S_IXUSR)
5581 			return (0);
5582 		goto out_error;
5583 	}
5584 
5585 	/* Otherwise, check the groups (first match) */
5586 	if (groupmember(file_gid, cred)) {
5587 		if (file_mode & S_IXGRP)
5588 			return (0);
5589 		goto out_error;
5590 	}
5591 
5592 	/* Otherwise, check everyone else. */
5593 	if (file_mode & S_IXOTH)
5594 		return (0);
5595 out_error:
5596 	/*
5597 	 * Permission check failed, but it is possible denial will get overwritten
5598 	 * (e.g., when root is traversing through a 700 directory owned by someone
5599 	 * else).
5600 	 *
5601 	 * vaccess() calls priv_check_cred which in turn can descent into MAC
5602 	 * modules overriding this result. It's quite unclear what semantics
5603 	 * are allowed for them to operate, thus for safety we don't call them
5604 	 * from within the SMR section. This also means if any such modules
5605 	 * are present, we have to let the regular lookup decide.
5606 	 */
5607 	error = priv_check_cred_vfs_lookup_nomac(cred);
5608 	switch (error) {
5609 	case 0:
5610 		return (0);
5611 	case EAGAIN:
5612 		/*
5613 		 * MAC modules present.
5614 		 */
5615 		return (EAGAIN);
5616 	case EPERM:
5617 		return (EACCES);
5618 	default:
5619 		return (error);
5620 	}
5621 }
5622 
5623 /*
5624  * Common filesystem object access control check routine.  Accepts a
5625  * vnode's type, "mode", uid and gid, requested access mode, and credentials.
5626  * Returns 0 on success, or an errno on failure.
5627  */
5628 int
5629 vaccess(__enum_uint8(vtype) type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
5630     accmode_t accmode, struct ucred *cred)
5631 {
5632 	accmode_t dac_granted;
5633 	accmode_t priv_granted;
5634 
5635 	KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
5636 	    ("invalid bit in accmode"));
5637 	KASSERT((accmode & VAPPEND) == 0 || (accmode & VWRITE),
5638 	    ("VAPPEND without VWRITE"));
5639 
5640 	/*
5641 	 * Look for a normal, non-privileged way to access the file/directory
5642 	 * as requested.  If it exists, go with that.
5643 	 */
5644 
5645 	dac_granted = 0;
5646 
5647 	/* Check the owner. */
5648 	if (cred->cr_uid == file_uid) {
5649 		dac_granted |= VADMIN;
5650 		if (file_mode & S_IXUSR)
5651 			dac_granted |= VEXEC;
5652 		if (file_mode & S_IRUSR)
5653 			dac_granted |= VREAD;
5654 		if (file_mode & S_IWUSR)
5655 			dac_granted |= (VWRITE | VAPPEND);
5656 
5657 		if ((accmode & dac_granted) == accmode)
5658 			return (0);
5659 
5660 		goto privcheck;
5661 	}
5662 
5663 	/* Otherwise, check the groups (first match) */
5664 	if (groupmember(file_gid, cred)) {
5665 		if (file_mode & S_IXGRP)
5666 			dac_granted |= VEXEC;
5667 		if (file_mode & S_IRGRP)
5668 			dac_granted |= VREAD;
5669 		if (file_mode & S_IWGRP)
5670 			dac_granted |= (VWRITE | VAPPEND);
5671 
5672 		if ((accmode & dac_granted) == accmode)
5673 			return (0);
5674 
5675 		goto privcheck;
5676 	}
5677 
5678 	/* Otherwise, check everyone else. */
5679 	if (file_mode & S_IXOTH)
5680 		dac_granted |= VEXEC;
5681 	if (file_mode & S_IROTH)
5682 		dac_granted |= VREAD;
5683 	if (file_mode & S_IWOTH)
5684 		dac_granted |= (VWRITE | VAPPEND);
5685 	if ((accmode & dac_granted) == accmode)
5686 		return (0);
5687 
5688 privcheck:
5689 	/*
5690 	 * Build a privilege mask to determine if the set of privileges
5691 	 * satisfies the requirements when combined with the granted mask
5692 	 * from above.  For each privilege, if the privilege is required,
5693 	 * bitwise or the request type onto the priv_granted mask.
5694 	 */
5695 	priv_granted = 0;
5696 
5697 	if (type == VDIR) {
5698 		/*
5699 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
5700 		 * requests, instead of PRIV_VFS_EXEC.
5701 		 */
5702 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5703 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP))
5704 			priv_granted |= VEXEC;
5705 	} else {
5706 		/*
5707 		 * Ensure that at least one execute bit is on. Otherwise,
5708 		 * a privileged user will always succeed, and we don't want
5709 		 * this to happen unless the file really is executable.
5710 		 */
5711 		if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
5712 		    (file_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0 &&
5713 		    !priv_check_cred(cred, PRIV_VFS_EXEC))
5714 			priv_granted |= VEXEC;
5715 	}
5716 
5717 	if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
5718 	    !priv_check_cred(cred, PRIV_VFS_READ))
5719 		priv_granted |= VREAD;
5720 
5721 	if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
5722 	    !priv_check_cred(cred, PRIV_VFS_WRITE))
5723 		priv_granted |= (VWRITE | VAPPEND);
5724 
5725 	if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
5726 	    !priv_check_cred(cred, PRIV_VFS_ADMIN))
5727 		priv_granted |= VADMIN;
5728 
5729 	if ((accmode & (priv_granted | dac_granted)) == accmode) {
5730 		return (0);
5731 	}
5732 
5733 	return ((accmode & VADMIN) ? EPERM : EACCES);
5734 }
5735 
5736 /*
5737  * Credential check based on process requesting service, and per-attribute
5738  * permissions.
5739  */
5740 int
5741 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
5742     struct thread *td, accmode_t accmode)
5743 {
5744 
5745 	/*
5746 	 * Kernel-invoked always succeeds.
5747 	 */
5748 	if (cred == NOCRED)
5749 		return (0);
5750 
5751 	/*
5752 	 * Do not allow privileged processes in jail to directly manipulate
5753 	 * system attributes.
5754 	 */
5755 	switch (attrnamespace) {
5756 	case EXTATTR_NAMESPACE_SYSTEM:
5757 		/* Potentially should be: return (EPERM); */
5758 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM));
5759 	case EXTATTR_NAMESPACE_USER:
5760 		return (VOP_ACCESS(vp, accmode, cred, td));
5761 	default:
5762 		return (EPERM);
5763 	}
5764 }
5765 
5766 #ifdef INVARIANTS
5767 void
5768 assert_vi_locked(struct vnode *vp, const char *str)
5769 {
5770 	VNASSERT(mtx_owned(VI_MTX(vp)), vp,
5771 	    ("%s: vnode interlock is not locked but should be", str));
5772 }
5773 
5774 void
5775 assert_vi_unlocked(struct vnode *vp, const char *str)
5776 {
5777 	VNASSERT(!mtx_owned(VI_MTX(vp)), vp,
5778 	    ("%s: vnode interlock is locked but should not be", str));
5779 }
5780 
5781 void
5782 assert_vop_locked(struct vnode *vp, const char *str)
5783 {
5784 	bool locked;
5785 
5786 	if (KERNEL_PANICKED() || vp == NULL)
5787 		return;
5788 
5789 #ifdef WITNESS
5790 	locked = !((vp->v_irflag & VIRF_CROSSMP) == 0 &&
5791 	    witness_is_owned(&vp->v_vnlock->lock_object) == -1);
5792 #else
5793 	int state = VOP_ISLOCKED(vp);
5794 	locked = state != 0 && state != LK_EXCLOTHER;
5795 #endif
5796 	VNASSERT(locked, vp, ("%s: vnode is not locked but should be", str));
5797 }
5798 
5799 void
5800 assert_vop_unlocked(struct vnode *vp, const char *str)
5801 {
5802 	bool locked;
5803 
5804 	if (KERNEL_PANICKED() || vp == NULL)
5805 		return;
5806 
5807 #ifdef WITNESS
5808 	locked = (vp->v_irflag & VIRF_CROSSMP) == 0 &&
5809 	    witness_is_owned(&vp->v_vnlock->lock_object) == 1;
5810 #else
5811 	locked = VOP_ISLOCKED(vp) == LK_EXCLUSIVE;
5812 #endif
5813 	VNASSERT(!locked, vp, ("%s: vnode is locked but should not be", str));
5814 }
5815 
5816 void
5817 assert_vop_elocked(struct vnode *vp, const char *str)
5818 {
5819 	bool locked;
5820 
5821 	if (KERNEL_PANICKED() || vp == NULL)
5822 		return;
5823 
5824 	locked = VOP_ISLOCKED(vp) == LK_EXCLUSIVE;
5825 	VNASSERT(locked, vp,
5826 	    ("%s: vnode is not exclusive locked but should be", str));
5827 }
5828 #endif /* INVARIANTS */
5829 
5830 void
5831 vop_rename_fail(struct vop_rename_args *ap)
5832 {
5833 
5834 	if (ap->a_tvp != NULL)
5835 		vput(ap->a_tvp);
5836 	if (ap->a_tdvp == ap->a_tvp)
5837 		vrele(ap->a_tdvp);
5838 	else
5839 		vput(ap->a_tdvp);
5840 	vrele(ap->a_fdvp);
5841 	vrele(ap->a_fvp);
5842 }
5843 
5844 void
5845 vop_rename_pre(void *ap)
5846 {
5847 	struct vop_rename_args *a = ap;
5848 
5849 #ifdef INVARIANTS
5850 	struct mount *tmp;
5851 
5852 	if (a->a_tvp)
5853 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
5854 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
5855 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
5856 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
5857 
5858 	/* Check the source (from). */
5859 	if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
5860 	    (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
5861 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
5862 	if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
5863 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
5864 
5865 	/* Check the target. */
5866 	if (a->a_tvp)
5867 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
5868 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
5869 
5870 	tmp = NULL;
5871 	VOP_GETWRITEMOUNT(a->a_tdvp, &tmp);
5872 	lockmgr_assert(&tmp->mnt_renamelock, KA_XLOCKED);
5873 	vfs_rel(tmp);
5874 #endif
5875 	/*
5876 	 * It may be tempting to add vn_seqc_write_begin/end calls here and
5877 	 * in vop_rename_post but that's not going to work out since some
5878 	 * filesystems relookup vnodes mid-rename. This is probably a bug.
5879 	 *
5880 	 * For now filesystems are expected to do the relevant calls after they
5881 	 * decide what vnodes to operate on.
5882 	 */
5883 	if (a->a_tdvp != a->a_fdvp)
5884 		vhold(a->a_fdvp);
5885 	if (a->a_tvp != a->a_fvp)
5886 		vhold(a->a_fvp);
5887 	vhold(a->a_tdvp);
5888 	if (a->a_tvp)
5889 		vhold(a->a_tvp);
5890 }
5891 
5892 #ifdef INVARIANTS
5893 void
5894 vop_fplookup_vexec_debugpre(void *ap __unused)
5895 {
5896 
5897 	VFS_SMR_ASSERT_ENTERED();
5898 }
5899 
5900 void
5901 vop_fplookup_vexec_debugpost(void *ap, int rc)
5902 {
5903 	struct vop_fplookup_vexec_args *a;
5904 	struct vnode *vp;
5905 
5906 	a = ap;
5907 	vp = a->a_vp;
5908 
5909 	VFS_SMR_ASSERT_ENTERED();
5910 	if (rc == EOPNOTSUPP)
5911 		VNPASS(VN_IS_DOOMED(vp), vp);
5912 }
5913 
5914 void
5915 vop_fplookup_symlink_debugpre(void *ap __unused)
5916 {
5917 
5918 	VFS_SMR_ASSERT_ENTERED();
5919 }
5920 
5921 void
5922 vop_fplookup_symlink_debugpost(void *ap __unused, int rc __unused)
5923 {
5924 
5925 	VFS_SMR_ASSERT_ENTERED();
5926 }
5927 
5928 static void
5929 vop_fsync_debugprepost(struct vnode *vp, const char *name)
5930 {
5931 	struct mount *mp;
5932 
5933 	if (vp->v_type == VCHR)
5934 		;
5935 	/*
5936 	 * The shared vs. exclusive locking policy for fsync()
5937 	 * is actually determined by vp's write mount as indicated
5938 	 * by VOP_GETWRITEMOUNT(), which for stacked filesystems
5939 	 * may not be the same as vp->v_mount.  However, if the
5940 	 * underlying filesystem which really handles the fsync()
5941 	 * supports shared locking, the stacked filesystem must also
5942 	 * be prepared for its VOP_FSYNC() operation to be called
5943 	 * with only a shared lock.  On the other hand, if the
5944 	 * stacked filesystem claims support for shared write
5945 	 * locking but the underlying filesystem does not, and the
5946 	 * caller incorrectly uses a shared lock, this condition
5947 	 * should still be caught when the stacked filesystem
5948 	 * invokes VOP_FSYNC() on the underlying filesystem.
5949 	 */
5950 	else {
5951 		mp = NULL;
5952 		VOP_GETWRITEMOUNT(vp, &mp);
5953 		if (vn_lktype_write(mp, vp) == LK_SHARED)
5954 			ASSERT_VOP_LOCKED(vp, name);
5955 		else
5956 			ASSERT_VOP_ELOCKED(vp, name);
5957 		if (mp != NULL)
5958 			vfs_rel(mp);
5959 	}
5960 }
5961 
5962 void
5963 vop_fsync_debugpre(void *a)
5964 {
5965 	struct vop_fsync_args *ap;
5966 
5967 	ap = a;
5968 	vop_fsync_debugprepost(ap->a_vp, "fsync");
5969 }
5970 
5971 void
5972 vop_fsync_debugpost(void *a, int rc __unused)
5973 {
5974 	struct vop_fsync_args *ap;
5975 
5976 	ap = a;
5977 	vop_fsync_debugprepost(ap->a_vp, "fsync");
5978 }
5979 
5980 void
5981 vop_fdatasync_debugpre(void *a)
5982 {
5983 	struct vop_fdatasync_args *ap;
5984 
5985 	ap = a;
5986 	vop_fsync_debugprepost(ap->a_vp, "fsync");
5987 }
5988 
5989 void
5990 vop_fdatasync_debugpost(void *a, int rc __unused)
5991 {
5992 	struct vop_fdatasync_args *ap;
5993 
5994 	ap = a;
5995 	vop_fsync_debugprepost(ap->a_vp, "fsync");
5996 }
5997 
5998 void
5999 vop_strategy_debugpre(void *ap)
6000 {
6001 	struct vop_strategy_args *a;
6002 	struct buf *bp;
6003 
6004 	a = ap;
6005 	bp = a->a_bp;
6006 
6007 	/*
6008 	 * Cluster ops lock their component buffers but not the IO container.
6009 	 */
6010 	if ((bp->b_flags & B_CLUSTER) != 0)
6011 		return;
6012 
6013 	BUF_ASSERT_LOCKED(bp);
6014 }
6015 
6016 void
6017 vop_lock_debugpre(void *ap)
6018 {
6019 	struct vop_lock1_args *a = ap;
6020 
6021 	if ((a->a_flags & LK_INTERLOCK) == 0)
6022 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
6023 	else
6024 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
6025 }
6026 
6027 void
6028 vop_lock_debugpost(void *ap, int rc)
6029 {
6030 	struct vop_lock1_args *a = ap;
6031 
6032 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
6033 	if (rc == 0 && (a->a_flags & LK_EXCLOTHER) == 0)
6034 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
6035 }
6036 
6037 void
6038 vop_unlock_debugpre(void *ap)
6039 {
6040 	struct vop_unlock_args *a = ap;
6041 	struct vnode *vp = a->a_vp;
6042 
6043 	VNPASS(vn_get_state(vp) != VSTATE_UNINITIALIZED, vp);
6044 	ASSERT_VOP_LOCKED(vp, "VOP_UNLOCK");
6045 }
6046 
6047 void
6048 vop_need_inactive_debugpre(void *ap)
6049 {
6050 	struct vop_need_inactive_args *a = ap;
6051 
6052 	ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
6053 }
6054 
6055 void
6056 vop_need_inactive_debugpost(void *ap, int rc)
6057 {
6058 	struct vop_need_inactive_args *a = ap;
6059 
6060 	ASSERT_VI_LOCKED(a->a_vp, "VOP_NEED_INACTIVE");
6061 }
6062 #endif /* INVARIANTS */
6063 
6064 void
6065 vop_allocate_post(void *ap, int rc)
6066 {
6067 	struct vop_allocate_args *a;
6068 
6069 	a = ap;
6070 	if (rc == 0)
6071 		INOTIFY(a->a_vp, IN_MODIFY);
6072 }
6073 
6074 void
6075 vop_copy_file_range_post(void *ap, int rc)
6076 {
6077 	struct vop_copy_file_range_args *a;
6078 
6079 	a = ap;
6080 	if (rc == 0) {
6081 		INOTIFY(a->a_invp, IN_ACCESS);
6082 		INOTIFY(a->a_outvp, IN_MODIFY);
6083 	}
6084 }
6085 
6086 void
6087 vop_create_pre(void *ap)
6088 {
6089 	struct vop_create_args *a;
6090 	struct vnode *dvp;
6091 
6092 	a = ap;
6093 	dvp = a->a_dvp;
6094 	vn_seqc_write_begin(dvp);
6095 }
6096 
6097 void
6098 vop_create_post(void *ap, int rc)
6099 {
6100 	struct vop_create_args *a;
6101 	struct vnode *dvp;
6102 
6103 	a = ap;
6104 	dvp = a->a_dvp;
6105 	vn_seqc_write_end(dvp);
6106 	if (rc == 0) {
6107 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6108 		INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6109 	}
6110 }
6111 
6112 void
6113 vop_deallocate_post(void *ap, int rc)
6114 {
6115 	struct vop_deallocate_args *a;
6116 
6117 	a = ap;
6118 	if (rc == 0)
6119 		INOTIFY(a->a_vp, IN_MODIFY);
6120 }
6121 
6122 void
6123 vop_whiteout_pre(void *ap)
6124 {
6125 	struct vop_whiteout_args *a;
6126 	struct vnode *dvp;
6127 
6128 	a = ap;
6129 	dvp = a->a_dvp;
6130 	vn_seqc_write_begin(dvp);
6131 }
6132 
6133 void
6134 vop_whiteout_post(void *ap, int rc)
6135 {
6136 	struct vop_whiteout_args *a;
6137 	struct vnode *dvp;
6138 
6139 	a = ap;
6140 	dvp = a->a_dvp;
6141 	vn_seqc_write_end(dvp);
6142 }
6143 
6144 void
6145 vop_deleteextattr_pre(void *ap)
6146 {
6147 	struct vop_deleteextattr_args *a;
6148 	struct vnode *vp;
6149 
6150 	a = ap;
6151 	vp = a->a_vp;
6152 	vn_seqc_write_begin(vp);
6153 }
6154 
6155 void
6156 vop_deleteextattr_post(void *ap, int rc)
6157 {
6158 	struct vop_deleteextattr_args *a;
6159 	struct vnode *vp;
6160 
6161 	a = ap;
6162 	vp = a->a_vp;
6163 	vn_seqc_write_end(vp);
6164 	if (!rc) {
6165 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
6166 		INOTIFY(vp, IN_ATTRIB);
6167 	}
6168 }
6169 
6170 void
6171 vop_link_pre(void *ap)
6172 {
6173 	struct vop_link_args *a;
6174 	struct vnode *vp, *tdvp;
6175 
6176 	a = ap;
6177 	vp = a->a_vp;
6178 	tdvp = a->a_tdvp;
6179 	vn_seqc_write_begin(vp);
6180 	vn_seqc_write_begin(tdvp);
6181 }
6182 
6183 void
6184 vop_link_post(void *ap, int rc)
6185 {
6186 	struct vop_link_args *a;
6187 	struct vnode *vp, *tdvp;
6188 
6189 	a = ap;
6190 	vp = a->a_vp;
6191 	tdvp = a->a_tdvp;
6192 	vn_seqc_write_end(vp);
6193 	vn_seqc_write_end(tdvp);
6194 	if (!rc) {
6195 		VFS_KNOTE_LOCKED(vp, NOTE_LINK);
6196 		VFS_KNOTE_LOCKED(tdvp, NOTE_WRITE);
6197 		INOTIFY_NAME(vp, tdvp, a->a_cnp, _IN_ATTRIB_LINKCOUNT);
6198 		INOTIFY_NAME(vp, tdvp, a->a_cnp, IN_CREATE);
6199 	}
6200 }
6201 
6202 void
6203 vop_mkdir_pre(void *ap)
6204 {
6205 	struct vop_mkdir_args *a;
6206 	struct vnode *dvp;
6207 
6208 	a = ap;
6209 	dvp = a->a_dvp;
6210 	vn_seqc_write_begin(dvp);
6211 }
6212 
6213 void
6214 vop_mkdir_post(void *ap, int rc)
6215 {
6216 	struct vop_mkdir_args *a;
6217 	struct vnode *dvp;
6218 
6219 	a = ap;
6220 	dvp = a->a_dvp;
6221 	vn_seqc_write_end(dvp);
6222 	if (!rc) {
6223 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6224 		INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6225 	}
6226 }
6227 
6228 #ifdef INVARIANTS
6229 void
6230 vop_mkdir_debugpost(void *ap, int rc)
6231 {
6232 	struct vop_mkdir_args *a;
6233 
6234 	a = ap;
6235 	if (!rc)
6236 		cache_validate(a->a_dvp, *a->a_vpp, a->a_cnp);
6237 }
6238 #endif
6239 
6240 void
6241 vop_mknod_pre(void *ap)
6242 {
6243 	struct vop_mknod_args *a;
6244 	struct vnode *dvp;
6245 
6246 	a = ap;
6247 	dvp = a->a_dvp;
6248 	vn_seqc_write_begin(dvp);
6249 }
6250 
6251 void
6252 vop_mknod_post(void *ap, int rc)
6253 {
6254 	struct vop_mknod_args *a;
6255 	struct vnode *dvp;
6256 
6257 	a = ap;
6258 	dvp = a->a_dvp;
6259 	vn_seqc_write_end(dvp);
6260 	if (rc == 0) {
6261 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6262 		INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6263 	}
6264 }
6265 
6266 void
6267 vop_reclaim_post(void *ap, int rc)
6268 {
6269 	struct vop_reclaim_args *a;
6270 	struct vnode *vp;
6271 
6272 	a = ap;
6273 	vp = a->a_vp;
6274 	ASSERT_VOP_IN_SEQC(vp);
6275 	if (!rc) {
6276 		VFS_KNOTE_LOCKED(vp, NOTE_REVOKE);
6277 		INOTIFY_REVOKE(vp);
6278 	}
6279 }
6280 
6281 void
6282 vop_remove_pre(void *ap)
6283 {
6284 	struct vop_remove_args *a;
6285 	struct vnode *dvp, *vp;
6286 
6287 	a = ap;
6288 	dvp = a->a_dvp;
6289 	vp = a->a_vp;
6290 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
6291 	vn_seqc_write_begin(dvp);
6292 	vn_seqc_write_begin(vp);
6293 }
6294 
6295 void
6296 vop_remove_post(void *ap, int rc)
6297 {
6298 	struct vop_remove_args *a;
6299 	struct vnode *dvp, *vp;
6300 
6301 	a = ap;
6302 	dvp = a->a_dvp;
6303 	vp = a->a_vp;
6304 	vn_seqc_write_end(dvp);
6305 	vn_seqc_write_end(vp);
6306 	if (!rc) {
6307 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6308 		VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6309 		INOTIFY_NAME(vp, dvp, a->a_cnp, _IN_ATTRIB_LINKCOUNT);
6310 		INOTIFY_NAME(vp, dvp, a->a_cnp, IN_DELETE);
6311 	}
6312 }
6313 
6314 void
6315 vop_rename_post(void *ap, int rc)
6316 {
6317 	struct vop_rename_args *a = ap;
6318 	long hint;
6319 
6320 	if (!rc) {
6321 		hint = NOTE_WRITE;
6322 		if (a->a_fdvp == a->a_tdvp) {
6323 			if (a->a_tvp != NULL && a->a_tvp->v_type == VDIR)
6324 				hint |= NOTE_LINK;
6325 			VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6326 			VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6327 		} else {
6328 			hint |= NOTE_EXTEND;
6329 			if (a->a_fvp->v_type == VDIR)
6330 				hint |= NOTE_LINK;
6331 			VFS_KNOTE_UNLOCKED(a->a_fdvp, hint);
6332 
6333 			if (a->a_fvp->v_type == VDIR && a->a_tvp != NULL &&
6334 			    a->a_tvp->v_type == VDIR)
6335 				hint &= ~NOTE_LINK;
6336 			VFS_KNOTE_UNLOCKED(a->a_tdvp, hint);
6337 		}
6338 
6339 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
6340 		if (a->a_tvp)
6341 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
6342 		INOTIFY_MOVE(a->a_fvp, a->a_fdvp, a->a_fcnp, a->a_tvp,
6343 		    a->a_tdvp, a->a_tcnp);
6344 	}
6345 	if (a->a_tdvp != a->a_fdvp)
6346 		vdrop(a->a_fdvp);
6347 	if (a->a_tvp != a->a_fvp)
6348 		vdrop(a->a_fvp);
6349 	vdrop(a->a_tdvp);
6350 	if (a->a_tvp)
6351 		vdrop(a->a_tvp);
6352 }
6353 
6354 void
6355 vop_rmdir_pre(void *ap)
6356 {
6357 	struct vop_rmdir_args *a;
6358 	struct vnode *dvp, *vp;
6359 
6360 	a = ap;
6361 	dvp = a->a_dvp;
6362 	vp = a->a_vp;
6363 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
6364 	vn_seqc_write_begin(dvp);
6365 	vn_seqc_write_begin(vp);
6366 }
6367 
6368 void
6369 vop_rmdir_post(void *ap, int rc)
6370 {
6371 	struct vop_rmdir_args *a;
6372 	struct vnode *dvp, *vp;
6373 
6374 	a = ap;
6375 	dvp = a->a_dvp;
6376 	vp = a->a_vp;
6377 	vn_seqc_write_end(dvp);
6378 	vn_seqc_write_end(vp);
6379 	if (!rc) {
6380 		vp->v_vflag |= VV_UNLINKED;
6381 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE | NOTE_LINK);
6382 		VFS_KNOTE_LOCKED(vp, NOTE_DELETE);
6383 		INOTIFY_NAME(vp, dvp, a->a_cnp, IN_DELETE);
6384 	}
6385 }
6386 
6387 void
6388 vop_setattr_pre(void *ap)
6389 {
6390 	struct vop_setattr_args *a;
6391 	struct vnode *vp;
6392 
6393 	a = ap;
6394 	vp = a->a_vp;
6395 	vn_seqc_write_begin(vp);
6396 }
6397 
6398 void
6399 vop_setattr_post(void *ap, int rc)
6400 {
6401 	struct vop_setattr_args *a;
6402 	struct vnode *vp;
6403 
6404 	a = ap;
6405 	vp = a->a_vp;
6406 	vn_seqc_write_end(vp);
6407 	if (!rc) {
6408 		VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6409 		INOTIFY(vp, IN_ATTRIB);
6410 	}
6411 }
6412 
6413 void
6414 vop_setacl_pre(void *ap)
6415 {
6416 	struct vop_setacl_args *a;
6417 	struct vnode *vp;
6418 
6419 	a = ap;
6420 	vp = a->a_vp;
6421 	vn_seqc_write_begin(vp);
6422 }
6423 
6424 void
6425 vop_setacl_post(void *ap, int rc __unused)
6426 {
6427 	struct vop_setacl_args *a;
6428 	struct vnode *vp;
6429 
6430 	a = ap;
6431 	vp = a->a_vp;
6432 	vn_seqc_write_end(vp);
6433 }
6434 
6435 void
6436 vop_setextattr_pre(void *ap)
6437 {
6438 	struct vop_setextattr_args *a;
6439 	struct vnode *vp;
6440 
6441 	a = ap;
6442 	vp = a->a_vp;
6443 	vn_seqc_write_begin(vp);
6444 }
6445 
6446 void
6447 vop_setextattr_post(void *ap, int rc)
6448 {
6449 	struct vop_setextattr_args *a;
6450 	struct vnode *vp;
6451 
6452 	a = ap;
6453 	vp = a->a_vp;
6454 	vn_seqc_write_end(vp);
6455 	if (!rc) {
6456 		VFS_KNOTE_LOCKED(vp, NOTE_ATTRIB);
6457 		INOTIFY(vp, IN_ATTRIB);
6458 	}
6459 }
6460 
6461 void
6462 vop_symlink_pre(void *ap)
6463 {
6464 	struct vop_symlink_args *a;
6465 	struct vnode *dvp;
6466 
6467 	a = ap;
6468 	dvp = a->a_dvp;
6469 	vn_seqc_write_begin(dvp);
6470 }
6471 
6472 void
6473 vop_symlink_post(void *ap, int rc)
6474 {
6475 	struct vop_symlink_args *a;
6476 	struct vnode *dvp;
6477 
6478 	a = ap;
6479 	dvp = a->a_dvp;
6480 	vn_seqc_write_end(dvp);
6481 	if (!rc) {
6482 		VFS_KNOTE_LOCKED(dvp, NOTE_WRITE);
6483 		INOTIFY_NAME(*a->a_vpp, dvp, a->a_cnp, IN_CREATE);
6484 	}
6485 }
6486 
6487 void
6488 vop_open_post(void *ap, int rc)
6489 {
6490 	struct vop_open_args *a = ap;
6491 
6492 	if (!rc) {
6493 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_OPEN);
6494 		INOTIFY(a->a_vp, IN_OPEN);
6495 	}
6496 }
6497 
6498 void
6499 vop_close_post(void *ap, int rc)
6500 {
6501 	struct vop_close_args *a = ap;
6502 
6503 	if (!rc && (a->a_cred != NOCRED || /* filter out revokes */
6504 	    !VN_IS_DOOMED(a->a_vp))) {
6505 		VFS_KNOTE_LOCKED(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6506 		    NOTE_CLOSE_WRITE : NOTE_CLOSE);
6507 		INOTIFY(a->a_vp, (a->a_fflag & FWRITE) != 0 ?
6508 		    IN_CLOSE_WRITE : IN_CLOSE_NOWRITE);
6509 	}
6510 }
6511 
6512 void
6513 vop_read_post(void *ap, int rc)
6514 {
6515 	struct vop_read_args *a = ap;
6516 
6517 	if (!rc) {
6518 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_READ);
6519 		INOTIFY(a->a_vp, IN_ACCESS);
6520 	}
6521 }
6522 
6523 void
6524 vop_read_pgcache_post(void *ap, int rc)
6525 {
6526 	struct vop_read_pgcache_args *a = ap;
6527 
6528 	if (rc == 0) {
6529 		VFS_KNOTE_UNLOCKED(a->a_vp, NOTE_READ);
6530 		INOTIFY(a->a_vp, IN_ACCESS);
6531 	}
6532 }
6533 
6534 static struct knlist fs_knlist;
6535 
6536 static void
6537 vfs_event_init(void *arg)
6538 {
6539 	knlist_init_mtx(&fs_knlist, NULL);
6540 }
6541 /* XXX - correct order? */
6542 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
6543 
6544 void
6545 vfs_event_signal(fsid_t *fsid, uint32_t event, intptr_t data __unused)
6546 {
6547 
6548 	KNOTE_UNLOCKED(&fs_knlist, event);
6549 }
6550 
6551 static int	filt_fsattach(struct knote *kn);
6552 static void	filt_fsdetach(struct knote *kn);
6553 static int	filt_fsevent(struct knote *kn, long hint);
6554 
6555 const struct filterops fs_filtops = {
6556 	.f_isfd = 0,
6557 	.f_attach = filt_fsattach,
6558 	.f_detach = filt_fsdetach,
6559 	.f_event = filt_fsevent,
6560 	.f_copy = knote_triv_copy,
6561 };
6562 
6563 static int
6564 filt_fsattach(struct knote *kn)
6565 {
6566 
6567 	kn->kn_flags |= EV_CLEAR;
6568 	knlist_add(&fs_knlist, kn, 0);
6569 	return (0);
6570 }
6571 
6572 static void
6573 filt_fsdetach(struct knote *kn)
6574 {
6575 
6576 	knlist_remove(&fs_knlist, kn, 0);
6577 }
6578 
6579 static int
6580 filt_fsevent(struct knote *kn, long hint)
6581 {
6582 
6583 	kn->kn_fflags |= kn->kn_sfflags & hint;
6584 
6585 	return (kn->kn_fflags != 0);
6586 }
6587 
6588 static int
6589 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
6590 {
6591 	struct vfsidctl vc;
6592 	int error;
6593 	struct mount *mp;
6594 
6595 	if (req->newptr == NULL)
6596 		return (EINVAL);
6597 	error = SYSCTL_IN(req, &vc, sizeof(vc));
6598 	if (error)
6599 		return (error);
6600 	if (vc.vc_vers != VFS_CTL_VERS1)
6601 		return (EINVAL);
6602 	mp = vfs_getvfs(&vc.vc_fsid);
6603 	if (mp == NULL)
6604 		return (ENOENT);
6605 	/* ensure that a specific sysctl goes to the right filesystem. */
6606 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
6607 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
6608 		vfs_rel(mp);
6609 		return (EINVAL);
6610 	}
6611 	VCTLTOREQ(&vc, req);
6612 	error = VFS_SYSCTL(mp, vc.vc_op, req);
6613 	vfs_rel(mp);
6614 	return (error);
6615 }
6616 
6617 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLTYPE_OPAQUE | CTLFLAG_MPSAFE | CTLFLAG_WR,
6618     NULL, 0, sysctl_vfs_ctl, "",
6619     "Sysctl by fsid");
6620 
6621 /*
6622  * Function to initialize a va_filerev field sensibly.
6623  * XXX: Wouldn't a random number make a lot more sense ??
6624  */
6625 u_quad_t
6626 init_va_filerev(void)
6627 {
6628 	struct bintime bt;
6629 
6630 	getbinuptime(&bt);
6631 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
6632 }
6633 
6634 static int	filt_vfsread(struct knote *kn, long hint);
6635 static int	filt_vfswrite(struct knote *kn, long hint);
6636 static int	filt_vfsvnode(struct knote *kn, long hint);
6637 static void	filt_vfsdetach(struct knote *kn);
6638 static int	filt_vfsdump(struct proc *p, struct knote *kn,
6639 		    struct kinfo_knote *kin);
6640 static int	filt_vfscopy(struct knote *kn, struct proc *p1);
6641 
6642 static const struct filterops vfsread_filtops = {
6643 	.f_isfd = 1,
6644 	.f_detach = filt_vfsdetach,
6645 	.f_event = filt_vfsread,
6646 	.f_userdump = filt_vfsdump,
6647 	.f_copy = filt_vfscopy,
6648 };
6649 static const struct filterops vfswrite_filtops = {
6650 	.f_isfd = 1,
6651 	.f_detach = filt_vfsdetach,
6652 	.f_event = filt_vfswrite,
6653 	.f_userdump = filt_vfsdump,
6654 	.f_copy = filt_vfscopy,
6655 };
6656 static const struct filterops vfsvnode_filtops = {
6657 	.f_isfd = 1,
6658 	.f_detach = filt_vfsdetach,
6659 	.f_event = filt_vfsvnode,
6660 	.f_userdump = filt_vfsdump,
6661 	.f_copy = filt_vfscopy,
6662 };
6663 
6664 static void
6665 vfs_knllock(void *arg)
6666 {
6667 	struct vnode *vp = arg;
6668 
6669 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6670 }
6671 
6672 static void
6673 vfs_knlunlock(void *arg)
6674 {
6675 	struct vnode *vp = arg;
6676 
6677 	if (KNLIST_EMPTY(&vp->v_pollinfo->vpi_selinfo.si_note))
6678 		vp->v_v2flag &= ~V2_KNOTE;
6679 	VOP_UNLOCK(vp);
6680 }
6681 
6682 static void
6683 vfs_knl_assert_lock(void *arg, int what)
6684 {
6685 #ifdef INVARIANTS
6686 	struct vnode *vp = arg;
6687 
6688 	if (what == LA_LOCKED)
6689 		ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
6690 	else
6691 		ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
6692 #endif
6693 }
6694 
6695 int
6696 vfs_kqfilter(struct vop_kqfilter_args *ap)
6697 {
6698 	struct vnode *vp = ap->a_vp;
6699 	struct knote *kn = ap->a_kn;
6700 	struct knlist *knl;
6701 
6702 	KASSERT(vp->v_type != VFIFO || (kn->kn_filter != EVFILT_READ &&
6703 	    kn->kn_filter != EVFILT_WRITE),
6704 	    ("READ/WRITE filter on a FIFO leaked through"));
6705 	switch (kn->kn_filter) {
6706 	case EVFILT_READ:
6707 		kn->kn_fop = &vfsread_filtops;
6708 		break;
6709 	case EVFILT_WRITE:
6710 		kn->kn_fop = &vfswrite_filtops;
6711 		break;
6712 	case EVFILT_VNODE:
6713 		kn->kn_fop = &vfsvnode_filtops;
6714 		break;
6715 	default:
6716 		return (EINVAL);
6717 	}
6718 
6719 	kn->kn_hook = (caddr_t)vp;
6720 
6721 	v_addpollinfo(vp);
6722 	if (vp->v_pollinfo == NULL)
6723 		return (ENOMEM);
6724 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
6725 	vhold(vp);
6726 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
6727 	knlist_add(knl, kn, 1);
6728 	vp->v_v2flag |= V2_KNOTE;
6729 	VOP_UNLOCK(vp);
6730 
6731 	return (0);
6732 }
6733 
6734 /*
6735  * Detach knote from vnode
6736  */
6737 static void
6738 filt_vfsdetach(struct knote *kn)
6739 {
6740 	struct vnode *vp = (struct vnode *)kn->kn_hook;
6741 
6742 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
6743 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
6744 	vdrop(vp);
6745 }
6746 
6747 /*ARGSUSED*/
6748 static int
6749 filt_vfsread(struct knote *kn, long hint)
6750 {
6751 	struct vnode *vp = (struct vnode *)kn->kn_hook;
6752 	off_t size;
6753 	int res;
6754 
6755 	/*
6756 	 * filesystem is gone, so set the EOF flag and schedule
6757 	 * the knote for deletion.
6758 	 */
6759 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6760 		VI_LOCK(vp);
6761 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6762 		VI_UNLOCK(vp);
6763 		return (1);
6764 	}
6765 
6766 	if (vn_getsize_locked(vp, &size, curthread->td_ucred) != 0)
6767 		return (0);
6768 
6769 	VI_LOCK(vp);
6770 	kn->kn_data = size - kn->kn_fp->f_offset;
6771 	res = (kn->kn_sfflags & NOTE_FILE_POLL) != 0 || kn->kn_data != 0;
6772 	VI_UNLOCK(vp);
6773 	return (res);
6774 }
6775 
6776 /*ARGSUSED*/
6777 static int
6778 filt_vfswrite(struct knote *kn, long hint)
6779 {
6780 	struct vnode *vp = (struct vnode *)kn->kn_hook;
6781 
6782 	VI_LOCK(vp);
6783 
6784 	/*
6785 	 * filesystem is gone, so set the EOF flag and schedule
6786 	 * the knote for deletion.
6787 	 */
6788 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD))
6789 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
6790 
6791 	kn->kn_data = 0;
6792 	VI_UNLOCK(vp);
6793 	return (1);
6794 }
6795 
6796 static int
6797 filt_vfsvnode(struct knote *kn, long hint)
6798 {
6799 	struct vnode *vp = (struct vnode *)kn->kn_hook;
6800 	int res;
6801 
6802 	VI_LOCK(vp);
6803 	if (kn->kn_sfflags & hint)
6804 		kn->kn_fflags |= hint;
6805 	if (hint == NOTE_REVOKE || (hint == 0 && vp->v_type == VBAD)) {
6806 		kn->kn_flags |= EV_EOF;
6807 		VI_UNLOCK(vp);
6808 		return (1);
6809 	}
6810 	res = (kn->kn_fflags != 0);
6811 	VI_UNLOCK(vp);
6812 	return (res);
6813 }
6814 
6815 static int
6816 filt_vfsdump(struct proc *p, struct knote *kn, struct kinfo_knote *kin)
6817 {
6818 	struct vattr va;
6819 	struct vnode *vp;
6820 	char *fullpath, *freepath;
6821 	int error;
6822 
6823 	kin->knt_extdata = KNOTE_EXTDATA_VNODE;
6824 
6825 	vp = kn->kn_fp->f_vnode;
6826 	kin->knt_vnode.knt_vnode_type = vntype_to_kinfo(vp->v_type);
6827 
6828 	va.va_fsid = VNOVAL;
6829 	vn_lock(vp, LK_SHARED | LK_RETRY);
6830 	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
6831 	VOP_UNLOCK(vp);
6832 	if (error != 0)
6833 		return (error);
6834 	kin->knt_vnode.knt_vnode_fsid = va.va_fsid;
6835 	kin->knt_vnode.knt_vnode_fileid = va.va_fileid;
6836 
6837 	freepath = NULL;
6838 	fullpath = "-";
6839 	error = vn_fullpath(vp, &fullpath, &freepath);
6840 	if (error == 0) {
6841 		strlcpy(kin->knt_vnode.knt_vnode_fullpath, fullpath,
6842 		    sizeof(kin->knt_vnode.knt_vnode_fullpath));
6843 	}
6844 	if (freepath != NULL)
6845 		free(freepath, M_TEMP);
6846 
6847 	return (0);
6848 }
6849 
6850 static int
6851 filt_vfscopy(struct knote *kn, struct proc *p1)
6852 {
6853 	struct vnode *vp;
6854 
6855 	vp = (struct vnode *)kn->kn_hook;
6856 	vhold(vp);
6857 	return (0);
6858 }
6859 
6860 int
6861 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
6862 {
6863 	int error;
6864 
6865 	if (dp->d_reclen > ap->a_uio->uio_resid)
6866 		return (ENAMETOOLONG);
6867 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
6868 	if (error) {
6869 		if (ap->a_ncookies != NULL) {
6870 			if (ap->a_cookies != NULL)
6871 				free(ap->a_cookies, M_TEMP);
6872 			ap->a_cookies = NULL;
6873 			*ap->a_ncookies = 0;
6874 		}
6875 		return (error);
6876 	}
6877 	if (ap->a_ncookies == NULL)
6878 		return (0);
6879 
6880 	KASSERT(ap->a_cookies,
6881 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
6882 
6883 	*ap->a_cookies = realloc(*ap->a_cookies,
6884 	    (*ap->a_ncookies + 1) * sizeof(uint64_t), M_TEMP, M_WAITOK | M_ZERO);
6885 	(*ap->a_cookies)[*ap->a_ncookies] = off;
6886 	*ap->a_ncookies += 1;
6887 	return (0);
6888 }
6889 
6890 /*
6891  * The purpose of this routine is to remove granularity from accmode_t,
6892  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
6893  * VADMIN and VAPPEND.
6894  *
6895  * If it returns 0, the caller is supposed to continue with the usual
6896  * access checks using 'accmode' as modified by this routine.  If it
6897  * returns nonzero value, the caller is supposed to return that value
6898  * as errno.
6899  *
6900  * Note that after this routine runs, accmode may be zero.
6901  */
6902 int
6903 vfs_unixify_accmode(accmode_t *accmode)
6904 {
6905 	/*
6906 	 * There is no way to specify explicit "deny" rule using
6907 	 * file mode or POSIX.1e ACLs.
6908 	 */
6909 	if (*accmode & VEXPLICIT_DENY) {
6910 		*accmode = 0;
6911 		return (0);
6912 	}
6913 
6914 	/*
6915 	 * None of these can be translated into usual access bits.
6916 	 * Also, the common case for NFSv4 ACLs is to not contain
6917 	 * either of these bits. Caller should check for VWRITE
6918 	 * on the containing directory instead.
6919 	 */
6920 	if (*accmode & (VDELETE_CHILD | VDELETE))
6921 		return (EPERM);
6922 
6923 	if (*accmode & VADMIN_PERMS) {
6924 		*accmode &= ~VADMIN_PERMS;
6925 		*accmode |= VADMIN;
6926 	}
6927 
6928 	/*
6929 	 * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
6930 	 * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
6931 	 */
6932 	*accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
6933 
6934 	return (0);
6935 }
6936 
6937 /*
6938  * Clear out a doomed vnode (if any) and replace it with a new one as long
6939  * as the fs is not being unmounted. Return the root vnode to the caller.
6940  */
6941 static int __noinline
6942 vfs_cache_root_fallback(struct mount *mp, int flags, struct vnode **vpp)
6943 {
6944 	struct vnode *vp;
6945 	int error;
6946 
6947 restart:
6948 	if (mp->mnt_rootvnode != NULL) {
6949 		MNT_ILOCK(mp);
6950 		vp = mp->mnt_rootvnode;
6951 		if (vp != NULL) {
6952 			if (!VN_IS_DOOMED(vp)) {
6953 				vrefact(vp);
6954 				MNT_IUNLOCK(mp);
6955 				error = vn_lock(vp, flags);
6956 				if (error == 0) {
6957 					*vpp = vp;
6958 					return (0);
6959 				}
6960 				vrele(vp);
6961 				goto restart;
6962 			}
6963 			/*
6964 			 * Clear the old one.
6965 			 */
6966 			mp->mnt_rootvnode = NULL;
6967 		}
6968 		MNT_IUNLOCK(mp);
6969 		if (vp != NULL) {
6970 			vfs_op_barrier_wait(mp);
6971 			vrele(vp);
6972 		}
6973 	}
6974 	error = VFS_CACHEDROOT(mp, flags, vpp);
6975 	if (error != 0)
6976 		return (error);
6977 	if (mp->mnt_vfs_ops == 0) {
6978 		MNT_ILOCK(mp);
6979 		if (mp->mnt_vfs_ops != 0) {
6980 			MNT_IUNLOCK(mp);
6981 			return (0);
6982 		}
6983 		if (mp->mnt_rootvnode == NULL) {
6984 			vrefact(*vpp);
6985 			mp->mnt_rootvnode = *vpp;
6986 		} else {
6987 			if (mp->mnt_rootvnode != *vpp) {
6988 				if (!VN_IS_DOOMED(mp->mnt_rootvnode)) {
6989 					panic("%s: mismatch between vnode returned "
6990 					    " by VFS_CACHEDROOT and the one cached "
6991 					    " (%p != %p)",
6992 					    __func__, *vpp, mp->mnt_rootvnode);
6993 				}
6994 			}
6995 		}
6996 		MNT_IUNLOCK(mp);
6997 	}
6998 	return (0);
6999 }
7000 
7001 int
7002 vfs_cache_root(struct mount *mp, int flags, struct vnode **vpp)
7003 {
7004 	struct mount_pcpu *mpcpu;
7005 	struct vnode *vp;
7006 	int error;
7007 
7008 	if (!vfs_op_thread_enter(mp, &mpcpu))
7009 		return (vfs_cache_root_fallback(mp, flags, vpp));
7010 	vp = atomic_load_ptr(&mp->mnt_rootvnode);
7011 	if (vp == NULL || VN_IS_DOOMED(vp)) {
7012 		vfs_op_thread_exit(mp, mpcpu);
7013 		return (vfs_cache_root_fallback(mp, flags, vpp));
7014 	}
7015 	vrefact(vp);
7016 	vfs_op_thread_exit(mp, mpcpu);
7017 	error = vn_lock(vp, flags);
7018 	if (error != 0) {
7019 		vrele(vp);
7020 		return (vfs_cache_root_fallback(mp, flags, vpp));
7021 	}
7022 	*vpp = vp;
7023 	return (0);
7024 }
7025 
7026 struct vnode *
7027 vfs_cache_root_clear(struct mount *mp)
7028 {
7029 	struct vnode *vp;
7030 
7031 	/*
7032 	 * ops > 0 guarantees there is nobody who can see this vnode
7033 	 */
7034 	MPASS(mp->mnt_vfs_ops > 0);
7035 	vp = mp->mnt_rootvnode;
7036 	if (vp != NULL)
7037 		vn_seqc_write_begin(vp);
7038 	mp->mnt_rootvnode = NULL;
7039 	return (vp);
7040 }
7041 
7042 void
7043 vfs_cache_root_set(struct mount *mp, struct vnode *vp)
7044 {
7045 
7046 	MPASS(mp->mnt_vfs_ops > 0);
7047 	vrefact(vp);
7048 	mp->mnt_rootvnode = vp;
7049 }
7050 
7051 /*
7052  * These are helper functions for filesystems to traverse all
7053  * their vnodes.  See MNT_VNODE_FOREACH_ALL() in sys/mount.h.
7054  *
7055  * This interface replaces MNT_VNODE_FOREACH.
7056  */
7057 
7058 struct vnode *
7059 __mnt_vnode_next_all(struct vnode **mvp, struct mount *mp)
7060 {
7061 	struct vnode *vp;
7062 
7063 	maybe_yield();
7064 	MNT_ILOCK(mp);
7065 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7066 	for (vp = TAILQ_NEXT(*mvp, v_nmntvnodes); vp != NULL;
7067 	    vp = TAILQ_NEXT(vp, v_nmntvnodes)) {
7068 		/* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
7069 		if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
7070 			continue;
7071 		VI_LOCK(vp);
7072 		if (VN_IS_DOOMED(vp)) {
7073 			VI_UNLOCK(vp);
7074 			continue;
7075 		}
7076 		break;
7077 	}
7078 	if (vp == NULL) {
7079 		__mnt_vnode_markerfree_all(mvp, mp);
7080 		/* MNT_IUNLOCK(mp); -- done in above function */
7081 		mtx_assert(MNT_MTX(mp), MA_NOTOWNED);
7082 		return (NULL);
7083 	}
7084 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
7085 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
7086 	MNT_IUNLOCK(mp);
7087 	return (vp);
7088 }
7089 
7090 struct vnode *
7091 __mnt_vnode_first_all(struct vnode **mvp, struct mount *mp)
7092 {
7093 	struct vnode *vp;
7094 
7095 	*mvp = vn_alloc_marker(mp);
7096 	MNT_ILOCK(mp);
7097 	MNT_REF(mp);
7098 
7099 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
7100 		/* Allow a racy peek at VIRF_DOOMED to save a lock acquisition. */
7101 		if (vp->v_type == VMARKER || VN_IS_DOOMED(vp))
7102 			continue;
7103 		VI_LOCK(vp);
7104 		if (VN_IS_DOOMED(vp)) {
7105 			VI_UNLOCK(vp);
7106 			continue;
7107 		}
7108 		break;
7109 	}
7110 	if (vp == NULL) {
7111 		MNT_REL(mp);
7112 		MNT_IUNLOCK(mp);
7113 		vn_free_marker(*mvp);
7114 		*mvp = NULL;
7115 		return (NULL);
7116 	}
7117 	TAILQ_INSERT_AFTER(&mp->mnt_nvnodelist, vp, *mvp, v_nmntvnodes);
7118 	MNT_IUNLOCK(mp);
7119 	return (vp);
7120 }
7121 
7122 void
7123 __mnt_vnode_markerfree_all(struct vnode **mvp, struct mount *mp)
7124 {
7125 
7126 	if (*mvp == NULL) {
7127 		MNT_IUNLOCK(mp);
7128 		return;
7129 	}
7130 
7131 	mtx_assert(MNT_MTX(mp), MA_OWNED);
7132 
7133 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7134 	TAILQ_REMOVE(&mp->mnt_nvnodelist, *mvp, v_nmntvnodes);
7135 	MNT_REL(mp);
7136 	MNT_IUNLOCK(mp);
7137 	vn_free_marker(*mvp);
7138 	*mvp = NULL;
7139 }
7140 
7141 /*
7142  * These are helper functions for filesystems to traverse their
7143  * lazy vnodes.  See MNT_VNODE_FOREACH_LAZY() in sys/mount.h
7144  */
7145 static void
7146 mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
7147 {
7148 
7149 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7150 
7151 	MNT_ILOCK(mp);
7152 	MNT_REL(mp);
7153 	MNT_IUNLOCK(mp);
7154 	vn_free_marker(*mvp);
7155 	*mvp = NULL;
7156 }
7157 
7158 /*
7159  * Relock the mp mount vnode list lock with the vp vnode interlock in the
7160  * conventional lock order during mnt_vnode_next_lazy iteration.
7161  *
7162  * On entry, the mount vnode list lock is held and the vnode interlock is not.
7163  * The list lock is dropped and reacquired.  On success, both locks are held.
7164  * On failure, the mount vnode list lock is held but the vnode interlock is
7165  * not, and the procedure may have yielded.
7166  */
7167 static bool
7168 mnt_vnode_next_lazy_relock(struct vnode *mvp, struct mount *mp,
7169     struct vnode *vp)
7170 {
7171 
7172 	VNASSERT(mvp->v_mount == mp && mvp->v_type == VMARKER &&
7173 	    TAILQ_NEXT(mvp, v_lazylist) != NULL, mvp,
7174 	    ("%s: bad marker", __func__));
7175 	VNASSERT(vp->v_mount == mp && vp->v_type != VMARKER, vp,
7176 	    ("%s: inappropriate vnode", __func__));
7177 	ASSERT_VI_UNLOCKED(vp, __func__);
7178 	mtx_assert(&mp->mnt_listmtx, MA_OWNED);
7179 
7180 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, mvp, v_lazylist);
7181 	TAILQ_INSERT_BEFORE(vp, mvp, v_lazylist);
7182 
7183 	/*
7184 	 * Note we may be racing against vdrop which transitioned the hold
7185 	 * count to 0 and now waits for the ->mnt_listmtx lock. This is fine,
7186 	 * if we are the only user after we get the interlock we will just
7187 	 * vdrop.
7188 	 */
7189 	vhold(vp);
7190 	mtx_unlock(&mp->mnt_listmtx);
7191 	VI_LOCK(vp);
7192 	if (VN_IS_DOOMED(vp)) {
7193 		VNPASS((vp->v_mflag & VMP_LAZYLIST) == 0, vp);
7194 		goto out_lost;
7195 	}
7196 	VNPASS(vp->v_mflag & VMP_LAZYLIST, vp);
7197 	/*
7198 	 * There is nothing to do if we are the last user.
7199 	 */
7200 	if (!refcount_release_if_not_last(&vp->v_holdcnt))
7201 		goto out_lost;
7202 	mtx_lock(&mp->mnt_listmtx);
7203 	return (true);
7204 out_lost:
7205 	vdropl(vp);
7206 	maybe_yield();
7207 	mtx_lock(&mp->mnt_listmtx);
7208 	return (false);
7209 }
7210 
7211 static struct vnode *
7212 mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7213     void *cbarg)
7214 {
7215 	struct vnode *vp;
7216 
7217 	mtx_assert(&mp->mnt_listmtx, MA_OWNED);
7218 	KASSERT((*mvp)->v_mount == mp, ("marker vnode mount list mismatch"));
7219 restart:
7220 	vp = TAILQ_NEXT(*mvp, v_lazylist);
7221 	while (vp != NULL) {
7222 		if (vp->v_type == VMARKER) {
7223 			vp = TAILQ_NEXT(vp, v_lazylist);
7224 			continue;
7225 		}
7226 		/*
7227 		 * See if we want to process the vnode. Note we may encounter a
7228 		 * long string of vnodes we don't care about and hog the list
7229 		 * as a result. Check for it and requeue the marker.
7230 		 */
7231 		VNPASS(!VN_IS_DOOMED(vp), vp);
7232 		if (!cb(vp, cbarg)) {
7233 			if (!should_yield()) {
7234 				vp = TAILQ_NEXT(vp, v_lazylist);
7235 				continue;
7236 			}
7237 			TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp,
7238 			    v_lazylist);
7239 			TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp,
7240 			    v_lazylist);
7241 			mtx_unlock(&mp->mnt_listmtx);
7242 			kern_yield(PRI_USER);
7243 			mtx_lock(&mp->mnt_listmtx);
7244 			goto restart;
7245 		}
7246 		/*
7247 		 * Try-lock because this is the wrong lock order.
7248 		 */
7249 		if (!VI_TRYLOCK(vp) &&
7250 		    !mnt_vnode_next_lazy_relock(*mvp, mp, vp))
7251 			goto restart;
7252 		KASSERT(vp->v_type != VMARKER, ("locked marker %p", vp));
7253 		KASSERT(vp->v_mount == mp || vp->v_mount == NULL,
7254 		    ("alien vnode on the lazy list %p %p", vp, mp));
7255 		VNPASS(vp->v_mount == mp, vp);
7256 		VNPASS(!VN_IS_DOOMED(vp), vp);
7257 		break;
7258 	}
7259 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7260 
7261 	/* Check if we are done */
7262 	if (vp == NULL) {
7263 		mtx_unlock(&mp->mnt_listmtx);
7264 		mnt_vnode_markerfree_lazy(mvp, mp);
7265 		return (NULL);
7266 	}
7267 	TAILQ_INSERT_AFTER(&mp->mnt_lazyvnodelist, vp, *mvp, v_lazylist);
7268 	mtx_unlock(&mp->mnt_listmtx);
7269 	ASSERT_VI_LOCKED(vp, "lazy iter");
7270 	return (vp);
7271 }
7272 
7273 struct vnode *
7274 __mnt_vnode_next_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7275     void *cbarg)
7276 {
7277 
7278 	maybe_yield();
7279 	mtx_lock(&mp->mnt_listmtx);
7280 	return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7281 }
7282 
7283 struct vnode *
7284 __mnt_vnode_first_lazy(struct vnode **mvp, struct mount *mp, mnt_lazy_cb_t *cb,
7285     void *cbarg)
7286 {
7287 	struct vnode *vp;
7288 
7289 	if (TAILQ_EMPTY(&mp->mnt_lazyvnodelist))
7290 		return (NULL);
7291 
7292 	*mvp = vn_alloc_marker(mp);
7293 	MNT_ILOCK(mp);
7294 	MNT_REF(mp);
7295 	MNT_IUNLOCK(mp);
7296 
7297 	mtx_lock(&mp->mnt_listmtx);
7298 	vp = TAILQ_FIRST(&mp->mnt_lazyvnodelist);
7299 	if (vp == NULL) {
7300 		mtx_unlock(&mp->mnt_listmtx);
7301 		mnt_vnode_markerfree_lazy(mvp, mp);
7302 		return (NULL);
7303 	}
7304 	TAILQ_INSERT_BEFORE(vp, *mvp, v_lazylist);
7305 	return (mnt_vnode_next_lazy(mvp, mp, cb, cbarg));
7306 }
7307 
7308 void
7309 __mnt_vnode_markerfree_lazy(struct vnode **mvp, struct mount *mp)
7310 {
7311 
7312 	if (*mvp == NULL)
7313 		return;
7314 
7315 	mtx_lock(&mp->mnt_listmtx);
7316 	TAILQ_REMOVE(&mp->mnt_lazyvnodelist, *mvp, v_lazylist);
7317 	mtx_unlock(&mp->mnt_listmtx);
7318 	mnt_vnode_markerfree_lazy(mvp, mp);
7319 }
7320 
7321 int
7322 vn_dir_check_exec(struct vnode *vp, struct componentname *cnp)
7323 {
7324 
7325 	if ((cnp->cn_flags & NOEXECCHECK) != 0) {
7326 		cnp->cn_flags &= ~NOEXECCHECK;
7327 		return (0);
7328 	}
7329 
7330 	return (VOP_ACCESS(vp, VEXEC, cnp->cn_cred, curthread));
7331 }
7332 
7333 /*
7334  * Do not use this variant unless you have means other than the hold count
7335  * to prevent the vnode from getting freed.
7336  */
7337 void
7338 vn_seqc_write_begin_locked(struct vnode *vp)
7339 {
7340 
7341 	ASSERT_VI_LOCKED(vp, __func__);
7342 	VNPASS(vp->v_holdcnt > 0, vp);
7343 	VNPASS(vp->v_seqc_users >= 0, vp);
7344 	vp->v_seqc_users++;
7345 	if (vp->v_seqc_users == 1)
7346 		seqc_sleepable_write_begin(&vp->v_seqc);
7347 }
7348 
7349 void
7350 vn_seqc_write_begin(struct vnode *vp)
7351 {
7352 
7353 	VI_LOCK(vp);
7354 	vn_seqc_write_begin_locked(vp);
7355 	VI_UNLOCK(vp);
7356 }
7357 
7358 void
7359 vn_seqc_write_end_locked(struct vnode *vp)
7360 {
7361 
7362 	ASSERT_VI_LOCKED(vp, __func__);
7363 	VNPASS(vp->v_seqc_users > 0, vp);
7364 	vp->v_seqc_users--;
7365 	if (vp->v_seqc_users == 0)
7366 		seqc_sleepable_write_end(&vp->v_seqc);
7367 }
7368 
7369 void
7370 vn_seqc_write_end(struct vnode *vp)
7371 {
7372 
7373 	VI_LOCK(vp);
7374 	vn_seqc_write_end_locked(vp);
7375 	VI_UNLOCK(vp);
7376 }
7377 
7378 /*
7379  * Special case handling for allocating and freeing vnodes.
7380  *
7381  * The counter remains unchanged on free so that a doomed vnode will
7382  * keep testing as in modify as long as it is accessible with SMR.
7383  */
7384 static void
7385 vn_seqc_init(struct vnode *vp)
7386 {
7387 
7388 	vp->v_seqc = 0;
7389 	vp->v_seqc_users = 0;
7390 }
7391 
7392 static void
7393 vn_seqc_write_end_free(struct vnode *vp)
7394 {
7395 
7396 	VNPASS(seqc_in_modify(vp->v_seqc), vp);
7397 	VNPASS(vp->v_seqc_users == 1, vp);
7398 }
7399 
7400 void
7401 vn_irflag_set_locked(struct vnode *vp, short toset)
7402 {
7403 	short flags;
7404 
7405 	ASSERT_VI_LOCKED(vp, __func__);
7406 	flags = vn_irflag_read(vp);
7407 	VNASSERT((flags & toset) == 0, vp,
7408 	    ("%s: some of the passed flags already set (have %d, passed %d)\n",
7409 	    __func__, flags, toset));
7410 	atomic_store_short(&vp->v_irflag, flags | toset);
7411 }
7412 
7413 void
7414 vn_irflag_set(struct vnode *vp, short toset)
7415 {
7416 
7417 	VI_LOCK(vp);
7418 	vn_irflag_set_locked(vp, toset);
7419 	VI_UNLOCK(vp);
7420 }
7421 
7422 void
7423 vn_irflag_set_cond_locked(struct vnode *vp, short toset)
7424 {
7425 	short flags;
7426 
7427 	ASSERT_VI_LOCKED(vp, __func__);
7428 	flags = vn_irflag_read(vp);
7429 	atomic_store_short(&vp->v_irflag, flags | toset);
7430 }
7431 
7432 void
7433 vn_irflag_set_cond(struct vnode *vp, short toset)
7434 {
7435 
7436 	VI_LOCK(vp);
7437 	vn_irflag_set_cond_locked(vp, toset);
7438 	VI_UNLOCK(vp);
7439 }
7440 
7441 void
7442 vn_irflag_unset_locked(struct vnode *vp, short tounset)
7443 {
7444 	short flags;
7445 
7446 	ASSERT_VI_LOCKED(vp, __func__);
7447 	flags = vn_irflag_read(vp);
7448 	VNASSERT((flags & tounset) == tounset, vp,
7449 	    ("%s: some of the passed flags not set (have %d, passed %d)\n",
7450 	    __func__, flags, tounset));
7451 	atomic_store_short(&vp->v_irflag, flags & ~tounset);
7452 }
7453 
7454 void
7455 vn_irflag_unset(struct vnode *vp, short tounset)
7456 {
7457 
7458 	VI_LOCK(vp);
7459 	vn_irflag_unset_locked(vp, tounset);
7460 	VI_UNLOCK(vp);
7461 }
7462 
7463 int
7464 vn_getsize_locked(struct vnode *vp, off_t *size, struct ucred *cred)
7465 {
7466 	struct vattr vattr;
7467 	int error;
7468 
7469 	ASSERT_VOP_LOCKED(vp, __func__);
7470 	error = VOP_GETATTR(vp, &vattr, cred);
7471 	if (__predict_true(error == 0)) {
7472 		if (vattr.va_size <= OFF_MAX)
7473 			*size = vattr.va_size;
7474 		else
7475 			error = EFBIG;
7476 	}
7477 	return (error);
7478 }
7479 
7480 int
7481 vn_getsize(struct vnode *vp, off_t *size, struct ucred *cred)
7482 {
7483 	int error;
7484 
7485 	VOP_LOCK(vp, LK_SHARED);
7486 	error = vn_getsize_locked(vp, size, cred);
7487 	VOP_UNLOCK(vp);
7488 	return (error);
7489 }
7490 
7491 #ifdef INVARIANTS
7492 void
7493 vn_set_state_validate(struct vnode *vp, __enum_uint8(vstate) state)
7494 {
7495 
7496 	switch (vp->v_state) {
7497 	case VSTATE_UNINITIALIZED:
7498 		switch (state) {
7499 		case VSTATE_CONSTRUCTED:
7500 		case VSTATE_DESTROYING:
7501 			return;
7502 		default:
7503 			break;
7504 		}
7505 		break;
7506 	case VSTATE_CONSTRUCTED:
7507 		ASSERT_VOP_ELOCKED(vp, __func__);
7508 		switch (state) {
7509 		case VSTATE_DESTROYING:
7510 			return;
7511 		default:
7512 			break;
7513 		}
7514 		break;
7515 	case VSTATE_DESTROYING:
7516 		ASSERT_VOP_ELOCKED(vp, __func__);
7517 		switch (state) {
7518 		case VSTATE_DEAD:
7519 			return;
7520 		default:
7521 			break;
7522 		}
7523 		break;
7524 	case VSTATE_DEAD:
7525 		switch (state) {
7526 		case VSTATE_UNINITIALIZED:
7527 			return;
7528 		default:
7529 			break;
7530 		}
7531 		break;
7532 	}
7533 
7534 	vn_printf(vp, "invalid state transition %d -> %d\n", vp->v_state, state);
7535 	panic("invalid state transition %d -> %d\n", vp->v_state, state);
7536 }
7537 #endif
7538