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