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