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