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