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