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